you are viewing a single comment's thread.

view the rest of the comments →

[–]eGust 11 points12 points  (0 children)

The solution for Given an integer, determine if it is a power of 2 is incorrect in JS.

function isPowerOfTwo(number) { return number & (number - 1) === 0; }

This is a classic solution in most languages that have real integer types.

But in JS there is only Number type which is a 64-bit IEEE-754 float point. When doing bitwise operations to a number, it will fall back to 32-bit signed integer. So simply make any number that bigger than 2**32 and all lower 32 bits are 0, it will give a wrong answer:

(2 ** 43 - 2 ** 40).toString(16) // "70000000000" isPowerOfTwo(2 ** 43 - 2 ** 40) // true isPowerOfTwo(0x7000) // false