Leetcode 67. Add Binary (Easy) (cpp)
Tag: Math, String
Difficulty: Easy
/*
67. Add Binary (Easy)
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
*/
class Solution {
public:
string addBinary(string a, string b) {
int i = a.size(), j = b.size(), carry = 0;
string res;
while (i > 0 || j > 0 || carry > 0) {
int num1 = i > 0 ? a[(i--) - 1] - '0' : 0, num2 = j > 0 ? b[(j--) - 1] - '0' : 0;
carry += num1 + num2;
res = char(carry % 2 + '0') + res;
carry /= 2;
}
return res;
}
};