Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
class Solution {
public String addBinary(String a, String b) {
if(a.length()<b.length()) return addBinary(b,a);
StringBuilder sb = new StringBuilder();
int i = a.length()-1;//a下标
int j = b.length()-1;//b下标
int add = 0;//进位
//System.out.println(a.length()-b.length() - 1);
while(i >= 0&& j >=0){
int x = Integer.parseInt(a.charAt(i)+"");
int y = Integer.parseInt(b.charAt(j)+"");
int temp = (x + y + add);
int z = temp % 2;
add = temp / 2;
sb.append(z);
i--;
j--;
}
while(i>=0){
int x = Integer.parseInt(a.charAt(i)+"");
int temp = (x + add);
int z = temp % 2;
add = temp / 2;
sb.append(z);
i--;
}
if(add!=0) sb.append(1);
return sb.reverse().toString();
}
}