Power of Four

LeetCode #342


Description:

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Follow up: Could you solve it without loops/recursion?

Example:

Example:
Given num = 16, return true. Given num = 5, return false.

Idea:

看是不是power of 2,然后再看能不能被3整除。

$$ a^{n+1}-b^{n+1}=(a-b)(a^n+a b^{n-1}+...+b^{n})

$$

Code:

class Solution {
public:
    bool isPowerOfFour(int num) {
        if(num<=0) return false;

        return ((num&(num-1))==0) && ((num-1) % 3 == 0);
    }
};

results matching ""

    No results matching ""