Given two binary strings a
and b
, return their sum as a binary string.
Input: a = "11", b = "1"
Output: "100"
Input: a = "1010", b = "1011"
Output: "10101"
a
and b
).#include <string>
#include <algorithm>
std::string addBinary(std::string a, std::string b) {
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
std::string result = "";
while (i >= 0 || j >= 0 || carry) {
int sum = carry;
if (i >= 0) {
sum += a[i] - '0';
i--;
}
if (j >= 0) {
sum += b[j] - '0';
j--;
}
carry = sum / 2;
result += std::to_string(sum % 2);
}
std::reverse(result.begin(), result.end());
return result;
}
i
and j
at the end of strings a
and b
respectively.carry
variable handles any overflow from the sum of two digits.a
or b
or there is a carry:
sum
as the sum of the carry and the current digits of a
and b
if available.sum % 2
) to the result string.n
and m
are the lengths of strings a
and b
respectively, because we process each bit once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?