67. Add Binary
Difficulty: Easy
Topics: Math, String
Similar Questions:
Problem:
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"
Solutions:
class Solution {
public:
string addBinary(string a, string b) {
string ret;
int carry = 0;
int indexA = a.length() - 1;
int indexB = b.length() - 1;
while (indexA >= 0 || indexB >= 0) {
int digitA = 0;
int digitB = 0;
if (indexA >= 0) {
digitA = a[indexA--] - '0';
}
if (indexB >= 0) {
digitB = b[indexB--] - '0';
}
int val = carry + digitA + digitB;
ret.push_back('0' + val%2);
carry = val/2;
}
if (carry == 1) ret.push_back('1');
reverse(ret.begin(), ret.end());
return ret;
}
};