Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
public class Solution {
public String addBinary(String a, String b) {
int m = a.length(),n = b.length();
String rec = "";
int maxLen = Math.max(m,n);
int carry = 0;
for(int i=maxLen-1;i>=0;i--)
{
int p=0,q=0;
if(m>0)
p = a.charAt(--m)-'0';
else
p = 0;
if(n>0)
q = b.charAt(--n)-'0';
else
q = 0;
int sum = p + q + carry;
carry = sum/2;
rec = sum%2 + rec; //直接转换为String类型
}
return carry == 0 ? rec : "1"+rec;
}
}