Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
public class AddBinarySolution {
public String addBinary(String a, String b) {
/**
* 二进制加法
* 从低位开始加,carry记住进位
* 最后结果逆序输出
*/
int aLen = a.length() - 1;
int bLen = b.length() - 1;
int carry = 0;
StringBuilder stringBuilder = new StringBuilder();
while (aLen >= 0 || bLen >= 0) {
int tempSum = carry;
if (aLen >= 0) tempSum += (a.charAt(aLen--) - '0');
if (bLen >= 0) tempSum += (b.charAt(bLen--) - '0');
stringBuilder.append(tempSum % 2);
carry = tempSum / 2;
}
if (carry != 0) stringBuilder.append(carry);
return stringBuilder.reverse().toString();
}
}