Description:

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n == 4x.

也就說,要判斷給定的 n 是不是 4 的指數次方

當 n 等於 1(=40), 4, 16, 64, 256,… 回傳 true 否則回傳 false.

Naive solution

Idea

將 n 拿去除以 4 若無法整除則回傳 false 否則除到商為 1.

bool isPowerOfFour(int n){
    if (n<1) return false;     
    while(n!=1){         
        if (n%4 != 0) return false;         
        n/=4;     
    }
    return true;
}

Another solution

Idea

The power of 4 in binary will start with one and end with an even number of zero.

  • 1 = 0x1
  • 4 = 0x100
  • 16 = 0x10000
  • …

Steps

two steps to check if n is the power of 4

  1. Use and operation to check lastest two bit is double zero
  2. Right offset with two-digit and check recursively.
bool isPowerOfFour(int n){
    if (n<1){ return false; }
    else if (n==1){ return true; }
    else if ((n & 3) == 0) { return isPowerOfFour(n>>2);}
    else { return false; } 
}

Solution without loops/recursion

Idea

There’s a way to check if number is power of 2 with AND bitwise operation.

!(n & (n - 1))

Which and make sure n is power of 2.

And if n is power of 4 can be devided by 3 after subtract 1.

(n - 1) % 3 == 0

Combile all of them with check if n is larger then zero.

return n > 0 && !(n & (n - 1)) && (n - 1) % 3 == 0;

Notes

The pure bitwise operation get the shortest runtime on leetcode platform.