【leetcode】 342. power of four

版权声明:来自 T2777 ,请访问 https://blog.csdn.net/T2777 一起交流进步吧 https://blog.csdn.net/T2777/article/details/86767127

题目:

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

Example 1:

Input: 16
Output: true

Example 2:

Input: 5
Output: false

验证所给数是否是4的幂,上一题刚解决了2的幂,判断同样适用于4的幂,但4的幂要增加判断条件,代码为:

class Solution {
public:
    bool isPowerOfFour(int num) {
        if(num <= 0)
            return false;
        //5 = 0101, 4 = 0100,16 = 00010000,64 = 01000000
        return ((num&(num-1)) == 0 && (num & 0x55555555));
    }
};

猜你喜欢

转载自blog.csdn.net/T2777/article/details/86767127
今日推荐