- 这道题遇到的最大的问题就是关于int隐式转换为char时报错
- 这一道题主要使用Stringbuffer来减少字符串上复制的开销
- 关键之一就是两个二进制求和的结果长度最多比较长的数字长1
思路:
- 首先将a字符串设置为较长的那一个
- 开辟两个Stringbuffer,较长的那一个数字头部多加一个0
- 另一个较短的前部补0到两者长度相同,方便计算
- 计算,进位,循环
- 设置最高位
class Solution {
public String addBinary(String a, String b) {
if(a.length() < b.length()){
String temp = a;
a = b;
b = temp;
}
StringBuilder addOne = new StringBuilder("0");
addOne.append(a);
StringBuilder addTwo = new StringBuilder();
int diff = addOne.length()-b.length();
while(diff>=0){
addTwo.append("0");
diff--;
}
addTwo.append(b);
int carryin = 0,sum = 0;
for(int i = addOne.length()-1;i>0;i--){
sum = (int)(addOne.charAt(i)-'0')+(int)(addTwo.charAt(i)-'0')+carryin;
if(sum%2 == 1)
addOne.setCharAt(i, '1');
else
addOne.setCharAt(i, '0');
carryin = sum /2;
}
if(carryin == 0){
addOne.deleteCharAt(0);
return addOne.toString();
}else{
addOne.setCharAt(0, '1');
return addOne.toString();
}
}
}
用到的Stringbuffer API总结:
StringBuffer:::deleteCharAt(int index)
StringBuffer:::setCharAt(int index,char chr)
StringBuffer:::CharAt(int index)
StringBuffer:::append(…) //在尾部增添字符串