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) {
char[] binary1 = a.toCharArray();
char[] binary2 = b.toCharArray();
String result = "";
if(binary1.length >=binary2.length){
result = diffAdd(binary1, binary2);
}
else
result = diffAdd(binary2, binary1);
return result;
}
public String diffAdd(char[] b1, char[] b2){
int len1 = b1.length - 1;
int len2 = b2.length - 1;
int count = 0; //进位
String ret = ""; //结果
while(len1>=0){ //由于b1长
if(len2 < 0){ //b2没有字符的时候,只有b1还有字符的时候
if(count == 1){ //判断进位,需要进位,则需要哦判断b1当前位置的字符
if(b1[len1] == '1'){ //判断b1, 为1,则结果是0,并且需要进位
ret = "0" + ret;
count = 1;
}
else{ //为0,则结果为1,并且不需要进位
ret = "1" + ret;
count = 0;
}
}
else //不需要进位,则不需要判断字符,直接copy
ret = b1[len1] + ret;
len1--;
}
else{ //b1、b2都有字符
if(b1[len1]=='1' && b2[len2]=='1'){ //需要进位
if(count == 1) //判断前一位有没有进位,如果有,则为1
ret= "1" + ret;
else
ret = "0" + ret;
count = 1;
}
else if(b1[len1]=='0' && b2[len2]=='0'){ //不需要进位
if(count == 1){
ret = "1" + ret;
count = 0;
}
else
ret = "0" + ret;
}
else{ //b1是1,或者b2是1
if(count == 1) //有进位,并且需要进位
ret = "0" + ret;
else //没有进位,也不需要进位
ret = "1" + ret;
}
len1--;
len2--;
}
}
if(count == 1)
ret = "1" + ret;
return ret;
}
}