67. Add Binary
Asked at 16Google53Bloomberg53Meta52Amazon50Microsoft50Wipro63Deloitte59Capgemini52tcs50Snap45Walmart Labs43Zoho42Visa39IBM35Infosys30Yandex28
Problem
Return the sum of two binary strings a and b as a binary string.
Example: "11" + "1" → "100"; "1010" + "1011" → "10101"
Add from the right with a carry, like decimal addition in base 2.
Complexity: O(max(m, n)).
class Solution:
def addBinary(self, a: str, b: str) -> str:
i, j, carry, out = len(a) - 1, len(b) - 1, 0, []
while i >= 0 or j >= 0 or carry:
s = carry + (int(a[i]) if i >= 0 else 0) + (int(b[j]) if j >= 0 else 0)
out.append(str(s % 2))
carry = s // 2
i, j = i - 1, j - 1
return "".join(reversed(out))
assert Solution().addBinary("11", "1") == "100"
assert Solution().addBinary("1010", "1011") == "10101"
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
for (int i = a.length() - 1, j = b.length() - 1, carry = 0; i >= 0 || j >= 0 || carry > 0; i--, j--) {
int s = carry + (i >= 0 ? a.charAt(i) - '0' : 0) + (j >= 0 ? b.charAt(j) - '0' : 0);
sb.append(s % 2);
carry = s / 2;
}
return sb.reverse().toString();
}
}
func addBinary(a string, b string) string {
out := []byte{}
for i, j, carry := len(a)-1, len(b)-1, 0; i >= 0 || j >= 0 || carry > 0; i, j = i-1, j-1 {
s := carry
if i >= 0 {
s += int(a[i] - '0')
}
if j >= 0 {
s += int(b[j] - '0')
}
out = append(out, byte('0'+s%2))
carry = s / 2
}
for l, r := 0, len(out)-1; l < r; l, r = l+1, r-1 {
out[l], out[r] = out[r], out[l]
}
return string(out)
}