1. 程式人生 > >LintCode Add Binary 二進位制求和

LintCode Add Binary 二進位制求和

給定兩個二進位制字串,返回他們的和(用二進位制表示)。

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

樣例

a = 11

b = 1

返回 100

public class Solution {
    /**
     * @param a a number
     * @param b a number
     * @return the result
     */
    public String addBinary(String a, String b) {
        if (a.length() < b.length()) {
            String temp = a;
            a = b;
            b = temp;
        }
        int alen = a.length(), blen = b.length();
        StringBuilder sb = new StringBuilder("");
        int carry = 0;
        int i = 0;
        for (; i < blen; i++) {
            int sum = carry + a.charAt(alen - 1 - i) + b.charAt(blen -1 - i) - 2 * '0';
            char cur = (char)('0' + sum % 2);
            carry = sum / 2;
            sb.insert(0, cur);
        }
        for (; i < alen; i++) {
            int sum = carry + a.charAt(alen - 1 - i) - '0';
            char cur = (char)('0' + sum % 2);
            carry = sum / 2;
            sb.insert(0, cur);
        }
        if (carry != 0) { sb.insert(0, (char)('0' + carry)); }
        return sb.toString();
    }
}