LeetCode: Add Binary 解题报告

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

For example,
a = "11"
b = "1"
Return "100".

SOLUTION:

指针指到两个字符串的末尾,不断往前推进,用carry表示进位。用stringbuilder来记录结果。

使用insert(0, c)函数将加出的结果不断插入到STRINGBUILDER.

 public class Solution {
public String addBinary(String a, String b) {
if (a == null || b == null) {
return null;
} if (a.length() == 0) {
return b;
} if (b.length() == 0) {
return a;
} StringBuilder sb = new StringBuilder(); int p1 = a.length() - 1;
int p2 = b.length() - 1; int carry = 0;
while (p1 >= 0 || p2 >= 0) {
int sum = carry;
if (p1 >= 0) {
sum += (a.charAt(p1) - '0');
} if (p2 >= 0) {
sum += (b.charAt(p2) - '0');
} char c = sum % 2 == 1 ? '1': '0';
sb.insert(0, c);
carry = sum / 2; p1--;
p2--;
} if (carry == 1) {
sb.insert(0, '1');
} return sb.toString();
}
}

GITHUB CODE:

AddBinary.java

上一篇:[LeetCode] 67. Add Binary 二进制数相加


下一篇:LeetCode Add Binary 两个二进制数相加