Add Binary

Easystringmathbit-manipulation
Category: Fundamentals
Companies that ask this question:
AmazonFacebookGoogle

Approach

Add Binary

Problem Statement

Given two binary strings a and b, return their sum as a binary string.

Examples

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Approach

Add binary digits from right to left with carry, just like decimal addition.

Complexity

  • Time: O(max(m, n))
  • Space: O(max(m, n))

Solution

java
1class Solution {
2    public String addBinary(String a, String b) {
3        StringBuilder result = new StringBuilder();
4        int i = a.length() - 1, j = b.length() - 1;
5        int carry = 0;
6        
7        while (i >= 0 || j >= 0 || carry > 0) {
8            int sum = carry;
9            if (i >= 0) sum += a.charAt(i--) - '0';
10            if (j >= 0) sum += b.charAt(j--) - '0';
11            result.append(sum % 2);
12            carry = sum / 2;
13        }
14        
15        return result.reverse().toString();
16    }
17}
Loading visualizer...