題目
描述
給定兩個二進制字符串,返回他們的和(用二進制表示)善绎。
樣例
a = 11
b = 1
返回 100
解答
思路
- 字符串拆成字符數(shù)組迅栅,遍歷字符數(shù)組進行計算,考慮到兩個字符串可能長短不同芦疏,先算短的一截(進位,兩個加數(shù)共三個參數(shù))微姊,再算長一點的字符串的剩余部分(進位酸茴,一個加數(shù)共兩個參數(shù))。
- 抽離按位相加功能兢交,返回參數(shù)中'1'的個數(shù)count薪捍,根據(jù)count進行不同處理。
- 注意字符串配喳,字符數(shù)組處理順序跟數(shù)字相加是反的飘诗,計算時要從右往左,存儲在緩存字符串中之后也要轉(zhuǎn)置界逛。
代碼
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;
}
}