给定两个二进制字符串,返回他们的和(用二进制表示)。
a = 11
b = 1
返回 100
public class Solution {
/**
* @param a a number
* @param b a number
* @return the result
*/
public String addBinary(String a, String b) {
// Write your code here
StringBuffer sb = new StringBuffer();
char carry = '0';
int count;
char[] as = a.toCharArray();
char[] bs = b.toCharArray();
char[] longer = (as.length > bs.length) ? as : bs;
int minLength = (as.length > bs.length) ? bs.length : as.length;
for (int i = 0; i < minLength; i++){
count = add(as[as.length - i - 1], bs[bs.length - i - 1], carry);
if(count == 0) {carry = '0';sb.append('0');}
else if(count == 1) {carry = '0';sb.append('1');}
else if(count == 2) {carry = '1';sb.append('0');}
else if(count == 3) {carry = '1';sb.append('1');}
else return "0";
}
for(int j = minLength; j < longer.length; j++){
count = add(longer[longer.length - j - 1], carry, '0');
if(count == 0) {carry = '0';sb.append('0');}
else if(count == 1) {carry = '0';sb.append('1');}
else if(count == 2) {carry = '1';sb.append('0');}
else return "0";
}
if(carry == '1') sb.append('1');
return sb.reverse().toString();
}
public int add(char a, char b, char c){
short count = 0;
count += ((a == '0') ? 0 : 1);
count += ((b == '0') ? 0 : 1);
count += ((c == '0') ? 0 : 1);
return count;
}
}