Very concise C++ solution without calculating longest string


  • 30
    A

    I am not sure if this can be made even more concise (possibly yes), but I believe this is sufficiently concise without sacrificing readability.

    string addBinary(string a, string b) 
    {
        string result = "";
        int apos = a.size() - 1;
        int bpos = b.size() - 1;
        int adigit, bdigit, carry = 0;
        
        while (apos >= 0 || bpos >= 0 || carry == 1)
        {
            adigit = bdigit = 0;
            
            if (apos >= 0) adigit = a[apos--] == '1';
            if (bpos >= 0) bdigit = b[bpos--] == '1';
            
            // Another way: the digit is 1 if adigit + bdigit + carry == 1 or == 3, but I noticed that
            // XOR is more concise:
            result = static_cast<char>(adigit ^ bdigit ^ carry + '0') + result; 
            carry = adigit + bdigit + carry >= 2;
        }
        
        return result;
    }

  • 0
    B

    nice solution~


  • 0
    C

    Good! The "carry==1" is easy to be ignored!


  • 0
    J

    that is used to compute the last digit.


Log in to reply
 

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