LeetCode-Add Binary
阿新 • • 發佈:2018-12-09
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 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
題意:給定兩個用字串表示的二進位制數字,求兩個二進位制數的和,並且也以二進位制字串的形式返回;
解法:我們可以從兩個串的尾部依次遍歷至串的首部,計算和時需要注意的是有進位的產生;有想過另外一個方法是將兩個字串轉換為數字求和後再表示為二進位制的形式後,以字串方式返回,但是可以字串的長度很長,求和後會產生溢位,因此還是使用字串來儲存;
class Solution {
public String addBinary(String a, String b) {
int carry = 0;
StringBuilder result = new StringBuilder();
int indexA = a.length() - 1;
int indexB = b.length() - 1;
while (indexA >= 0 || indexB >= 0) {
int xA = indexA >= 0 ? a.charAt(indexA--) - '0' : 0;
int xB = indexB >= 0 ? b.charAt(indexB--) - '0' : 0;
result.insert(0, (xA + xB + carry) % 2);
carry = (xA + xB + carry) / 2;
}
if (carry == 1) {
result.insert(0, "1");
}
return result.toString();
}
}