Sunday, May 1, 2016

[LintCode] 408 Add Binary 解题报告

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


Example 
a = 11
b = 1
Return 100 

思路
从后往前一位一位比。注意carry > 0的时候也要做一遍。否则会漏掉第一位的数字。

Code
public class Solution {
    /**
     * @param a a number
     * @param b a number
     * @return the result
     */
    public String addBinary(String a, String b) {
        // Write your code here
        StringBuilder res = new StringBuilder();
        int aLen = a.length() - 1;
        int bLen = b.length() - 1;
        int carry = 0;
        while (aLen >= 0 || bLen >= 0 || carry > 0) {
            int aa = aLen >= 0 ? a.charAt(aLen--) - '0' : 0;
            int bb = bLen >= 0 ? b.charAt(bLen--) - '0' : 0;
            res.append(aa ^ bb ^ carry);
            carry = aa + bb + carry > 1 ? 1 : 0;
        }
        return res.reverse().toString();
    }
}