[LeetCode] C++: Simple Question-Bit Operation Power of 342.4

342. Power of 4

Easy difficulty 160

Given an integer, write a function to determine whether it is a power of 4. If yes, return  true ; otherwise, return  false .

If the integer  n is a power of 4, it needs to satisfy: there are integers  x such that n == 4x

 

Example 1:

Input: n = 16
 Output: true

Example 2:

Input: n = 5
 Output: false

Example 3:

Input: n = 1
 Output: true

 

prompt:

  • -231 <= n <= 231 - 1

 

Advanced:

  • Can you solve this problem without using loops or recursion?

Magical world, mathematics formula 

class Solution {
public:
    bool isPowerOfFour(int n) { 
        if(n <= 0){
            return false;
        }
        double res = log(n) / log(4);
        if(res - (int)res == 0){
            return true;
        }
        return false;
    }
};

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/113758265
Recommended