LeetCode题解:Add Binary

Add Binary

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

For example,
a = "11"
b = "1"
Return "100".

思路:

小学编程竞赛题。

题解:

class Solution {
public:
    string addBinary(string a, string b) {
        bool carry = false;
        
        const int LenA = a.size();
        const int LenB = b.size();
        const int MaxLen = max(LenA, LenB);
        
        string ret;
        ret.resize(MaxLen);
        
        for(int i = 1; i <= MaxLen; ++i)
        {
            char ca = (LenA - i >= 0 ? a[LenA - i] - '0' : 0);
            char cb = (LenB - i >= 0 ? b[LenB - i] - '0' : 0);
            
            switch(ca + cb + carry)
            {
                case 3:
                    ret[MaxLen - i] = '1';
                    carry = true;
                    break;
                case 2:
                    ret[MaxLen - i] = '0';
                    carry = true;
                    break;
                case 1:
                    ret[MaxLen - i] = '1';
                    carry = false;
                    break;
                case 0:
                    ret[MaxLen - i] = '0';
                    carry = false;
                    break;
            }
        }
        
        if (carry)
            ret = string("1") + ret;
            
        return ret;
    }
};


你可能感兴趣的:(LeetCode)