题目描述:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
解题思路:
使用StringBuilder,且使用进位。
代码如下:
public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while(i >= 0 || j >= 0){
if(i >= 0) carry += a.charAt(i--) - '0';
if(j >= 0) carry += b.charAt(j--) - '0';
sb.insert(0, carry % 2);
carry /= 2;
}
if(carry > 0) sb.insert(0, carry);
return sb.toString();
}
}