[LeetCode] Add Binary

https://leetcode.com/problems/add-binary/

模拟加法操作,链表也有类似的问题(Add Two Numbers)。

/*
 * author : TK
 * date   : 2017-02-14
 * problem: LeetCode 67: Add Binary
 * method : simulate the operation of addition
 */ 
class Solution {
public:
    string addBinary(string a, string b) {
        int p1 = a.size() - 1, p2 = b.size() - 1, carry = 0;
        
        // simulate the addition operation
        string ret = "";
        while (true) {
            if (p1 >= 0) carry += (a[p1--] - '0');
            if (p2 >= 0) carry += (b[p2--] - '0');
            string next_digit = to_string(carry % 2);
            carry /= 2;
            if (p1 >= 0 || p2 >= 0 || carry != 0 || next_digit != "0") {
                ret = next_digit + ret;
            } else break;
        }
        
        // remove the prefix '0'
        int i = 0;
        while (i < ret.size()) {
            if (ret[i] != '0') break;
            i++;
        }
        if (ret.empty()) ret = "0";
        
        return ret.substr(i, ret.size() - i);
    }
};
posted @ 2017-02-15 22:11  mioopoi  阅读(115)  评论(0)    收藏  举报