Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Add Binary

C++, Python and TypeScript solutions for Add Binary.

The Add Binary solutions are below.

Solution files

Python•add-binary/synced-solution.py
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return bin(int(a, 2) + int(b, 2))[2:]
C++•add-binary/synced-solution.cpp
class Solution {
public:
    string addBinary(string a, string b) {
        string res = "";
        int carry = 0, i = a.size()-1, j = b.size()-1;
        while (i >= 0 || j >= 0 || carry) {
            int sum = carry;
            if (i >= 0) sum += a[i--] - '0';
            if (j >= 0) sum += b[j--] - '0';
            res = char('0' + sum%2) + res;
            carry = sum / 2;
        }
        return res.empty() ? "0" : res;
    }
};
TypeScript•add-binary/synced-solution.ts
function addBinary(a: string, b: string): string {
    return (BigInt('0b' + a) + BigInt('0b' + b)).toString(2);
}