从末尾开始相加,本位和进位,得到的本位直接替换掉长串的那一位;如果进位==0且短串已全部遍历完,则跳出循环;
跳出循环后,再判断进位是否>0,大于的补上1。
注意:
1.不能用long,因为字符串的长度方法返回的是int
2.char转化为int,int i = c - '0',ASCII码相减
3. StringBuilder的replace函数,见API
public String addBinary(String a, String b) {
int l1 = a.length()-1;
int l2 = b.length()-1;
int cha = Math.abs(l1-l2);
StringBuilder longStr = new StringBuilder();
StringBuilder shortStr = new StringBuilder();
if(l1 < l2){
longStr = new StringBuilder(b);
shortStr = new StringBuilder(a);
}else{
longStr = new StringBuilder(a);
shortStr = new StringBuilder(b);
}
int jin = 0;
int cur = 0;
int maxLen = longStr.length()-1;
for(int i = maxLen;i>=0;i--){
int lc = longStr.charAt(i)-'0';
int sc = 0;
if(i-cha >= 0){
sc = shortStr.charAt(i-cha)-'0';
}
cur = (lc+sc+jin)%2;
if(lc+sc+jin > 1){
jin = 1;
}else{
jin = 0;
}
longStr.replace(i, i+1, cur+"");
if((i-cha) < 0 && jin == 0)break;
}
if(jin > 0){
longStr.replace(0, 0, "1");
}
return longStr.toString();
}