p67

LeetCode p67 Add Binary 题解

1.题目:

Given two binary strings, return their sum (also a binary string).

For example,
a = “11”
b = “1”
Return “100”.

题意:

模拟二进制加法,输出二进制和。

2.解题思路:

见代码

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
public class Solution {
public String addBinary(String a, String b) {
int al = a.length() - 1;
int bl = b.length() - 1;
int c = 0;
StringBuilder stringBuilder = new StringBuilder();
while (al >= 0 || bl >= 0) {
int sum = 0;
if (al >= 0)
sum += a.charAt(al--) - '0';
if (bl >= 0)
sum += b.charAt(bl--) - '0';
sum += c;
stringBuilder.append(sum % 2);
c = sum / 2;
}
if (c == 1) stringBuilder.append(c);
return stringBuilder.reverse().toString();// 反转

}
}

4.一些总结: