[LintCode] Add Binary 二进制数相加

 

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

Example

a = 11

b = 1

Return 100

 

LeetCode上的原题,请参见我之前的博客Add Binary

 

class Solution {
public:
    /**
     * @param a a number
     * @param b a number
     * @return the result
     */
    string addBinary(string& a, string& b) {
        string res = "";
        int m = a.size() - 1, n = b.size() - 1, carry = 0;
        while (m >= 0 || n >= 0) {
            int p = m >= 0 ? a[m--] - '0' : 0;
            int q = n >= 0 ? b[n--] - '0' : 0;
            int sum = p + q + carry;
            res = to_string(sum % 2) + res;
            carry = sum / 2;
        }
        return carry == 1 ? "1" + res : res;
    }
};

 

posted @ 2016-08-20 14:55  Grandyang  阅读(996)  评论(0编辑  收藏  举报
Fork me on GitHub