3ms CPP easy to understand solution


  • 0
    D
    class Solution {
    public:
        string addBinary(string a, string b) {
            string result = "";
            int i = a.size()-1;
            int j = b.size()-1;
            int c = '0';
            while(i >= 0 || j >= 0 || c == '1') {
                int total = (i >= 0 ? a[i--] : '0') + (j >= 0 ? b[j--] : '0') + c;
                if (total == '1' + '1' + '1'){
                    c = '1';
                    result.insert(0,1,'1');
                }
                else if (total == '1' + '1' + '0'){
                    c = '1';
                    result.insert(0,1,'0');
                }
                else if (total == '1' + '0' + '0'){
                    c = '0';
                    result.insert(0,1,'1');
                }
                else{
                    result.insert(0,1, '0');
                }
            }
            
            return result;
        }
    };
    

    After seeing all of those other beautiful concise solutions I'm realizing that my code is kinda kludgy but much easier to reason about.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.