Given two binary strings, return their sum (also a binary string).

For example,
a = “11”
b = “1”
Return “100”.

public String addBinary(String a, String b) {
int res = BinaryToInt(a) + BinaryToInt(b);
return Integer.toBinaryString(res);
}
public int BinaryToInt(String num){
int res = 0;
for(int i = 0; i < num.length(); i++){
res += (Math.pow(2, i)) * (num.charAt(num.length() - i - 1) - '0');
}
return res;
}

public class Solution {
public String addBinary(String a, String b) {
a = reverseStr(a);
b = reverseStr(b);
String longerStr = a.length() > b.length() ? a : b;
String shortterStr = a.length() > b.length() ? b : a;
String res = "";
int i, tmp, carry = 0;
for(i = 0; i < shortterStr.length(); i++){
tmp = shortterStr.charAt(i) - '0' + longerStr.charAt(i) - '0' + carry;
if(tmp >= 2){
tmp -= 2;
carry = 1;
}else{
carry = 0;
}
res += String.valueOf((char)(tmp + '0'));
}
for(; i < longerStr.length(); i++){
tmp = longerStr.charAt(i) - '0' + carry;
if(tmp >= 2){
tmp -= 2;
carry = 1;
}else{
carry = 0;
}
res += String.valueOf((char)(tmp + '0'));
}
if(carry == 1) res += "1";
return reverseStr(res);
}
public String reverseStr(String s){
StringBuffer sb=new StringBuffer(s);
sb.reverse();
return sb.toString();
}
}

1. java中反转字符串的方法（利用StringBuffer）；
2. String.valueOf((char)(tmp + ‘0’))这里，要进行强制转换。

• 本文已收录于以下专栏：

举报原因： 您举报文章：[leetcode]Add Binary 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)