isPowerOfTwo
Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2^x.
Examples
isPowerOfTwo(1) → true
isPowerOfTwo(16) → true
isPowerOfTwo(3) → false
Starter code
function isPowerOfTwo(n) {
}
Complexity of the optimal solution
Time O(1), space O(1). This clever bit manipulation trick works in constant time. A power of two in binary is a 1 followed by all 0s (e.g., 16 is 10000). Subtracting 1 flips all bits up to that 1 (e.g., 15 is 01111). The bitwise AND of these two numbers will always be 0.