Monday, February 10, 2014

Leetcode: Add Binary

Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".

Solution:

public class Solution {
    public String addBinary(String a, String b) {
        StringBuilder solution = new StringBuilder();
        int sum = 0;
        for(int i = 0; i < Math.max(a.length(), b.length()); i++)   
        {
            sum += i<a.length() && a.charAt(a.length()-1-i) == '1' ? 1 : 0;
            sum += i<b.length() && b.charAt(b.length()-1-i) == '1' ? 1 : 0;
            solution.insert(0, sum% 2);
            sum /= 2;
        }
        if (sum >0)
            solution.insert(0, sum% 2);
        return solution.toString();
    }
}

No comments :

Post a Comment