LeetCode 342. Power of Four

Description

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.

Analysis

解法一:用(num & (num - 1)) == 0來確定num是2的冪,由於4的冪中,1只可能位於奇數位(最低位設爲第0位),則有num & 0x55555555 == num
解法二:思路同上,但使用的反向思維,所有的偶數位應都爲0,即num & 0xAAAAAAAA == 0
解法三:判斷是否2的冪同上,但判斷是否爲4的冪時,借用了3,即(num - 1) % 3 == 0

Code

Version 1

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

Version 2

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

Version 3

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

Appendix

Question: don’t know why the 2nd solution is slower than others…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章