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();
}
}