Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 67] Add Binary

Question

link

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

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

Stats

Frequency 4
Difficulty 2
Adjusted Difficulty 2
Time to use ----------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is an easy question. Pure coding.

There are some boundary issues during my first attempt. And special note to the trim() operation after “String.valueOf(ans)”, it’s easy to omit.

My code

public String addBinary(String a, String b) {
    int m = a.length(), n = b.length();
    char[] ans = new char[Math.max(m, n) + 1];
    int p = m - 1, q = n - 1, r = ans.length - 1;
    int carry = 0;
    while (r >= 0) {
        if (p >= 0)
            ans[r] += a.charAt(p--) - '0';
        if (q >= 0)
            ans[r] += b.charAt(q--) - '0';
        int temp = ans[r] + carry;
        ans[r] = (char) (temp % 2 + '0');
        carry = temp / 2;
        r--;
    }
    if (ans[0] == '0')
        ans[0] = ' ';
    return String.valueOf(ans).trim();
}