Power of Two
Problem
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 == 2x
.
Follow up: Could you solve it without loops/recursion?
Constraints
-231 <= nums[i] <= 231 - 1
Solution
The problem Power of Two
can be solved by examining bits in the given number. If and only if a given integer is a power of two, then subtracting 1 from the number and performing a bitwise and operation on 2 numbers will result in 0.
Implementation
class Solution
{
public:
bool isPowerOfTwo(int n) { return n > 0 && (n & n - 1) == 0; }
};