Algorithms and Data Structures · Senior · Question 48 of 75

What is the complexity of checking whether a number is a power of two with n > 0 && (n & (n - 1)) === 0?

Explanation

It's a single bitwise operation on a fixed-width integer. In JavaScript bitwise operators work on 32-bit integers, so for values above 2³¹ you need another approach, such as Number.isInteger(Math.log2(n)) or BigInt.

Further reading

Problem with a question

Algorithms and Data Structures · Senior · question 48

Test yourself

Take the Algorithms and Data Structures · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz