[leetcode刷题系列]Add Binary

- - 模拟题咯


class Solution {
public:
    string addBinary(string a, string b) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());
        string ans = "";
        int carry = 0;
        int len = max(a.size(), b.size());
        for(int i = 0; i < len; ++ i){
            int ca = 0;
            if(i < a.size())
                ca = a[i] - '0';
            int cb = 0;
            if(i < b.size())
                cb = b[i] - '0';
            int sum = ca + cb + carry;
            carry = sum / 2;
            ans += sum % 2 + '0';
        }
        if(carry)
            ans += '1';
        reverse(ans.begin(), ans.end());
        return ans;
    }
};


你可能感兴趣的:([leetcode刷题系列]Add Binary)