Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
public class Solution {
public String addBinary(String a, String b) {
if(a == null && b == null){
return null;
}
if(a == null){
return b;
}
if(b == null){
return a;
}
int lenA = a.length();
int lenB = b.length();
int len = Math.max(lenA, lenB);
int carry = 0;
String result = "";
for(int i=0; i<len; i++){
int p, q = 0;
if(i < lenA){
p = a.charAt(lenA-1-i) - '0'; //把字符转换成数字,从最末尾开始读
}else{
p = 0;
}
if(i < lenB){
q = b.charAt(lenB-1-i) - '0';
}else{
q = 0;
}
int tem = p + q + carry;
carry = tem/2;
result = tem%2 + result; //不能写成result += tem%2,顺序不一样
}
if(carry == 1){
result = "1" + result;
}
return result;
}
}