Add Binary

Problem

Given two binary strings, return their sum (also a binary string).

For example, a = "11" b = "1" Return "100".

Solution

StringBuilder: O(n) time, O(n) space

public class Solution {
    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder();
        int i = a.length() - 1, j = b.length() - 1, carry = 0;
        while (i >= 0 || j >= 0) {
            if (i >= 0) carry += a.charAt(i--) - '0';
            if (j >= 0) carry += b.charAt(j--) - '0';
            sb.append(carry % 2);
            carry /= 2;
        }
        if (carry != 0) sb.append(carry);
        return sb.reverse().toString();
    }
}

Analysis

A typical way to do calculation of two numbers
We just need to have separated indices for a and b and a var carry
Then we increment carry as long as a or b has value
We append carry to our StringBuilder then update carry by carry /= 2
Do not forget to add the last carry after the loop terminates!

results matching ""

    No results matching ""