LeetCode 67. Add Binary
Given two binary strings a
and b
, return their sum as a binary string.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
method
- 十进制加法,先两个加数求和,模以10作为当前位的结果,再除以10作进位
- 二进制加法,先两个加数求和,模以2作为当前位的结果,再除以2作进位
string addBinary(string a, string b) {
int carry = 0;
string res = "";
int i = a.size() - 1;
int j = b.size() - 1;
while (i >= 0 || j >= 0 || carry) {
carry += i >= 0 ? a[i--] - '0' : 0;
carry += j >= 0 ? b[j--] - '0' : 0;
res = char(carry % 2 + '0') + res;
carry = carry / 2;
}
return res;
}