-
Notifications
You must be signed in to change notification settings - Fork 0
/
67. Add Binary
56 lines (45 loc) · 1.64 KB
/
67. Add Binary
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
Given two binary strings a and b, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
Constraints:
1 <= a.length, b.length <= 104
a and b consist only of '0' or '1' characters.
Each string does not contain leading zeros except for the zero itself.
题目翻译:
给定两个二进制字符串 a 和 b,将它们的和作为二进制字符串返回。
class Solution {
// 定义方法,将两个二进制字符串相加并返回结果字符串
public String addBinary(String a, String b) {
// 创建一个StringBuilder来存储结果字符串
StringBuilder sb = new StringBuilder();
// 初始化两个字符串的下标和进位数
int i = a.length() - 1, j = b.length() - 1, carry = 0;
// 从末尾开始遍历两个字符串
while (i >= 0 || j >= 0) {
int sum = carry;
// 如果a字符串还有数字,将它加入sum
if (i >= 0) {
sum += a.charAt(i) - '0';
i--;
}
// 如果b字符串还有数字,将它加入sum
if (j >= 0) {
sum += b.charAt(j) - '0';
j--;
}
// 将sum的个位数加入结果字符串,carry为sum的十位数
sb.append(sum % 2);
carry = sum / 2;
}
// 如果还有进位,将其加入结果字符串
if (carry != 0) {
sb.append(carry);
}
// 返回结果字符串,需要先反转再转化为字符串
return sb.reverse().toString();
}
}