Add Binary (append, reverse)

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

For example,
a = “11”
b = “1”
Return “100”.

public class Solution {
    public String addBinary(String a, String b) {
        StringBuilder sb = new StringBuilder(); 
        //start i and j from the last char of given strings (ones)
        int i = a.length() - 1, j = b.length() - 1, carry = 0; 
        while (i >= 0 || j >= 0) {
            int sum = carry; 
            if (i >= 0) sum += a.charAt(i--) - '0';
            if (j >= 0) sum += b.charAt(j--) - '0';
            //append the new (higher) digit to the existing string
            //need to reverse it later
            sb.append(sum%2); 
            carry = sum/2; 
        }
        if (carry != 0) sb.append(carry);
        //need to reverse the string 
        return sb.reverse().toString(); 
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s