Problem · Bit Manipulation
Power of Two Without Division
Learn this problemProblem statement
Given a signed integer n, determine whether it is a positive power of two.
A positive integer is a power of two when it can be written as 2^k for an integer k >= 0. Your solution must not use division or a library exponentiation helper such as Math.pow.
Return true when n is a power of two and false otherwise.
Function
isPowerOfTwo(n: int) → booleanExamples
Example 1
n = 16return = true16 = 2^4, so the result is true.
Example 2
n = 18return = false18 is positive but cannot be written as a single power of two.
Example 3
n = 1return = true1 = 2^0, so it is a power of two.
Constraints
-2^31 <= n <= 2^31 - 1.1counts as a power of two.- Every value less than or equal to
0returnsfalse. - The solution must not use division or a library exponentiation helper.