LeetCode题目:67. 二进制求和
字符串相关题目,使用栈来实现
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58class Solution { public String addBinary(String a, String b) { Stack<Integer> num1 = new Stack<>(); Stack<Integer> num2 = new Stack<>(); Stack<Integer> sum = new Stack<>(); for (int i = 0; i < a.length(); i++) { num1.push(a.charAt(i) - '0'); } for (int i = 0; i < b.length(); i++) { num2.push(b.charAt(i) - '0'); } // temp用来表示进位 int temp = 0; while (!num1.isEmpty() && !num2.isEmpty()) { // x和y分别表示当前需要相加的两位 int x = num1.pop(); int y = num2.pop(); // 此时temp的值为前一位的进位 sum.push((x + y + temp) % 2); // 将temp更新为当前位相加的进位 if (x + y + temp >= 2) { temp = 1; } else { temp = 0; } } // 将两个数字中未进行计算的位数加到结果中,不要忘了考虑上面最后计算完的进位 while (!num1.isEmpty()) { int k = num1.pop(); sum.push((k + temp) % 2); if (k + temp >= 2) { temp = 1; } else { temp = 0; } } while (!num2.isEmpty()) { int k = num2.pop(); sum.push((k + temp) % 2); if (k + temp >= 2) { temp = 1; } else { temp = 0; } } // 考虑最后一位计算完的进位 if (temp == 1) { sum.push(temp); } // 依次出栈,拼接结果字符串 String result = ""; while (!sum.isEmpty()) { result += sum.pop(); } return result; } }
最后
以上就是危机导师最近收集整理的关于67. 二进制求和 LeetCode-字符串的全部内容,更多相关67.内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复