题目
描述
给定两个二进制字符串,返回他们的和(用二进制表示)。
样例
a = 11
b = 1
返回 100
解答
思路
- 字符串拆成字符数组,遍历字符数组进行计算,考虑到两个字符串可能长短不同,先算短的一截(进位,两个加数共三个参数),再算长一点的字符串的剩余部分(进位,一个加数共两个参数)。
- 抽离按位相加功能,返回参数中'1'的个数count,根据count进行不同处理。
- 注意字符串,字符数组处理顺序跟数字相加是反的,计算时要从右往左,存储在缓存字符串中之后也要转置。
代码
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;
}
}