[LeetCode] 342. Power of Four 4的次方数

Posted 轻风舞动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 342. Power of Four 4的次方数相关的知识,希望对你有一定的参考价值。

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

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

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

Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.

给一个有符号的32位整数,写一个函数检查此数是否为4的次方数。

解法1:位操作

解法2:循环

解法3: 数学函数, 换底公式

Java:

public boolean isPowerOfFour(int num) {
    int count0=0;
    int count1=0;
 
    while(num>0){
        if((num&1)==1){
            count1++;
        }else{
            count0++;
        }
 
        num>>=1;
    }
 
    return count1==1 && (count0%2==0);
}  

Java:

public boolean isPowerOfFour(int num) {
    while(num>0){
        if(num==1){
            return true;
        }
 
        if(num%4!=0){
            return false;
        }else{
            num=num/4;
        }
    }
 
    return false;
}

Java:

public boolean isPowerOfFour(int num) {
   if(num==0) return false;
 
   int pow = (int) (Math.log(num) / Math.log(4));
   if(num==Math.pow(4, pow)){
       return true;
   }else{
       return false;
   }
}

Python:

class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        return num > 0 and (num & (num - 1)) == 0 and \\
               ((num & 0b01010101010101010101010101010101) == num)

Python:

# Time:  O(1)
# Space: O(1)
class Solution2(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        while num and not (num & 0b11):
            num >>= 2
        return (num == 1)

C++:

class Solution {
public:
    bool isPowerOfFour(int num) {
        while (num && (num % 4 == 0)) {
            num /= 4;
        }
        return num == 1;
    }
};

C++:

class Solution {
public:
    bool isPowerOfFour(int num) {
        return num > 0 && int(log10(num) / log10(4)) - log10(num) / log10(4) == 0;
    }
};

C++:

class Solution {
public:
    bool isPowerOfFour(int num) {
        return num > 0 && !(num & (num - 1)) && (num & 0x55555555) == num;
    }
};

C++:  

class Solution {
public:
    bool isPowerOfFour(int num) {
        return num > 0 && !(num & (num - 1)) && (num - 1) % 3 == 0;
    }
};

   

类似题目:

[LeetCode] 231. Power of Two 2的次方数

[LeetCode] 326. Power of Three 3的次方数

 

All LeetCode Questions List 题目汇总

以上是关于[LeetCode] 342. Power of Four 4的次方数的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode191 Number of 1 Bits. LeetCode231 Power of Two. LeetCode342 Power of Four

[leetcode] 342. Power of Four

342. Power of Four(LeetCode)

LeetCode 342. Power of Four

leetcode 342. Power of Four

[leetcode-342-Power of Four]