Description
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example
Input: a = "11", b = "1"
Output: "100"
Input: a = "1010", b = "1011"
Output: "10101"
Solution
这道题刚做的时候感觉和《剑指Offer》上的一道很像,于是用了相同的思路写出下面的代码:
public class Solution {
public String addBinary(String a, String b) {
int num1 = Integer.valueOf(a, 2), num2 = Integer.valueOf(b, 2);
int sum = 0, carry = 0;
do {
sum = num1 ^ num2;
carry = (num1 & num2) << 1;
num1 = sum;
num2 = carry;
} while(carry != 0);
return Integer.toBinaryString(sum);
}
}
当字符串比较小的时候,这种解法是正确的,但是在leetcode上的测试用例字符串十分长,也就无法转换成int类型,因此只能考虑用别的办法。既然无法使用整型直接运算,那么只好一个字符一个字符的来。每次将两个二进制的某一位相加,可以发现在二进制加法运算中如果不考虑进位则0+0=0,0+1=1,1+1=0,而如果有上一位相加得到的进位,那么有可能发生1+1+1=1的情况,这些时候将不考虑进位的结果放入StringBuilder中,并保存进位,在下一位的计算中要加上进位,其它操作不变。
public class Solution2 {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while(i >= 0 || j >= 0) {
int lastCarry = carry;
int ca = i >= 0 ? a.charAt(i--)-'0' : 0;
int cb = j >= 0 ? b.charAt(j--)-'0' : 0;
sb.append(lastCarry ^ ca ^ cb);
carry = lastCarry == 0 ? ca & cb : ca | cb;
}
if (carry != 0)
sb.append(carry);
return sb.reverse().toString();
}
}