Thursday, January 8, 2015

LeetCode 67: Add Binary

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) {
        int m = a.length();
        int n = b.length();
        
        if (m == 0)
            return b;
        
        if (n == 0)
            return a;
        
        String result = "";
        int carry = 0;
        
        for (int i = 0; i < Math.max(m, n); i++)
        {
            if (i < m)
                carry += a.charAt(m-i-1)-'0';
                
            if (i < n)
                carry += b.charAt(n-i-1)-'0';
                
            result = String.valueOf(carry%2) + result;
            carry = carry/2;
        }
        
        if (carry > 0)
            result = Integer.toString(carry) + result;
            
        return result;
    }
}

No comments:

Post a Comment