LeetCode#67: Add Binary
阿新 • • 發佈:2018-11-17
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();
}
}