给定两个二进制字符串,返回他们的和(用二进制表示)。
样例
a = 11
b = 1
返回 100
解题思路:
与Lintcode 407:加一类似,写一个按位加法即可,只是这里注意a,b长度有差异,可能会出现一方加完了另一方还没加完,所以一共需要考虑三种情况。
第二个注意的点就是加到最后一位要考虑进位增加数的情况。
第三个注意的点是这样的按位加是倒序的,最后需要翻转一下。
最后需要注意这里的数字是字符形式,需要转换为数字形式再进行计算
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
char[] aa = a.toCharArray();
char[] bb = b.toCharArray();
StringBuilder sb = new StringBuilder();
int i=aa.length-1, j=bb.length-1;
int cnt = 0;
while(i>=0 || j>=0){
while(i>=0 && j>=0){
int temp = aa[i] - '0' + bb[j] - '0' + cnt;
sb.append(temp%2);
cnt = temp/2;
i--;
j--;
}
while(i >= 0){
int temp = aa[i] - '0' + cnt;
sb.append(temp%2);
cnt = temp/2;
i--;
}
while(j >= 0){
int temp = bb[j] - '0' + cnt;
sb.append(temp%2);
cnt = temp/2;
j--;
}
}
if(cnt != 0)
sb.append(cnt);
return sb.reverse().toString();
}
}