Given two binary strings, return their sum (also a binary string).
For example,
a ="11"
b ="1"
Return"100"
.
Solution: 不要忘记剩下的进位
public String addBinary(String a, String b) {
if (a == null || b == null) {
return "";
}
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, extra = 0;
while (i >= 0 && j >= 0) {
int sum = a.charAt(i) - '0' + b.charAt(j) - '0' + extra;
extra = sum / 2;
sum %= 2;
sb.append(sum);
i--;
j--;
}
while (i >= 0) {
int sum = a.charAt(i) - '0' + extra;
extra = sum / 2;
sum %= 2;
sb.append(sum);
i--;
}
while (j >= 0) {
int sum = b.charAt(j) - '0' + extra;
extra = sum / 2;
sum %= 2;
sb.append(sum);
j--;
}
//记得
if (extra != 0) {
sb.append(extra);
}
return sb.reverse().toString();
}