public String addBinary(String a, String b) {
// int carry=0;
// String result="";
// int i=0;
// int alen=a.length();
// int blen=b.length();
// while(i<alen||i<blen||carry!=0){
// int x=(i<alen)?((a.charAt(alen-1-i)=='1')?1:0):0;
// int y=(i<blen)?((b.charAt(blen-1-i)=='1')?1:0):0;
// result=(x+y+carry)%2+result;
// carry=(x+y+carry)/2;
// i++;
int carry = 0;
String res = "";
int i = 0;
int aLen = a.length();
int bLen = b.length();
while(i < aLen || i < bLen || carry != 0) {
int x = 0;
int y = 0;
if(i < aLen && a.charAt(aLen - 1 -i) == '1')
x = 1;
if(i < bLen && b.charAt(bLen - 1 -i) == '1')
y = 1;
res = (x+y+carry) % 2 + res;
carry = (x+y+carry) / 2;
i++;
}
return res;
}
Leave A Comment