class Solution {
public String addBinary(String a, String b) {
if(a.equals("0")){
return b;
}
if(b.equals("0")){
return a;
}
StringBuffer s_a = new StringBuffer(a);
StringBuffer s_b = new StringBuffer(b);
StringBuffer re_a = s_a.reverse();
StringBuffer re_b = s_b.reverse();
int c = 0;
StringBuffer s = new StringBuffer();
int len = Math.max(re_a.length(), re_b.length());
for(int i = 0; i < len; i++){
if(i < a.length())
c += re_a.charAt(i) - '0';
if(i < b.length())
c += re_b.charAt(i) - '0';
s.append((char)((c % 2) + '0'));
c /= 2;
}
if(c != 0){
s.append((char)(c + '0'));
}
return s.reverse().toString();
}
}
总结:
(1)字符串添加的时候,用StringBuffer,添加用.append(),用法:new StringBuffer(String s)
(2)StringBuffer才有reverse()方法,String没有