190. Reverse Bits

@shurui using << coerces the int to a 32-bit signed int, so the tests fail because it's interpreted as a negative value.

  • Using *= coerces it back to a JS float, which is interpreted as the correct positive value (JS floats can store its up to 53 bits)

  • You can still use result = result << 1 if you either (a) Math.abs(result) at the end before returning or (b) return result >>> 0 before returning. Both have the same effect.

This is documented here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

Without reading that or just knowing it, there's no way to reason out why << doesn't work.

Try reassigning result:

result = result << 1

which is the same as:

result *= 2

time: O(N)

space: O(32) > O(1)

/**
 * @param {number} n - a positive integer
 * @return {number} - a positive integer
 */
var reverseBits = function(n) {
    const bi = n.toString(2);
    const paded = bi.padStart(32, '0');
    const reversed = [...paded].reverse().join('');

    return parseInt(reversed, 2);
};

Last updated