PU Power of Two

Jan 01, 1970

Given an integer, write a function to determine if it is a power of two.

C Solution 1:

bool isPowerOfTwo(int n) {
    if (n <= 0) return false;
    for (; !(n & 1); n >>= 1);
    return !(n >> 1);
}

C Solution 2:

bool isPowerOfTwo(int n) {
    return n > 0 && !(n & (n - 1));
}

Summary:

  1. bit manipulation.
  2. find the first set bit, then right-shift this bit, check if the value is zero or not.
  3. 6ms, 0%

LeetCode: 231. Power of Two