Leetcode 67. Add Binary

smpl published on
1 min, 100 words

문제 : 67. Add Binary

등급 : Easy

class Solution {
public:
    string addBinary(string a, string b) {
        string ret;
        
        auto ait = a.rbegin();
        auto bit = b.rbegin();
        
        auto carry = 0;
        for (;;) {
            auto aempty = ait == a.rend();
            auto bempty = bit == b.rend();
            
            if (aempty && bempty) {
                if (carry) {
                    ret.push_back('1');
                }
                break;
            }
            
            auto a = 0;
            if (!aempty) {
                if (*ait != '0') {
                    a = 1;
                }
                
                ait++;
            }
            
            auto b = 0;
            if (!bempty) {
                if (*bit != '0') {
                    b = 1;
                }
                
                bit++;
            }
            
            auto sum = a + b + carry;
            
            char res = sum & 0x01 ? '1': '0';
            carry = sum & 0x02 ? 1 : 0;
            
            ret.push_back(res);
        }
        
        std::cout << ret.c_str() << std::endl;
        std::reverse(ret.begin(), ret.end());
        
        return ret;
    }
};