[practice js] beats 100.0%, with a little bit comments


  • 0
    M
    /**
     * @param {number} a
     * @param {number} b
     * @return {number}
     */
     // bit manipulation: add bits <--> xor bits
     // a and b could be negative
     // in javascript, bitwise operators treat their operands as a sequence of 32 bits (0s and 1s)
    var getSum = function(a, b) {
        for (var mask = 1, carry = 0; mask !== 0; mask <<= 1) {
            var aBit = a & mask;
            var bBit = b & mask;
            a ^= (bBit ^ (carry !== 0 ? mask : 0));
            if ((carry !== 0 && (aBit !== 0 || bBit !== 0)) || (aBit !== 0 && bBit !== 0)) {
                carry = 1;
            } else {
                carry = 0;
            }
        }
        return a;
    };
    

Log in to reply
 

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