【leetcode】342. Power of Four

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


思路:
(num&(num-1))==0保證整個二進制中只有一個1;(num-1) % 3 == 0保證1位於二進制中的偶數位上。


代碼實現:

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

參考:
https://leetcode.com/problems/power-of-four/discuss/80460/1-line-C%2B%2B-solution-without-confusing-bit-manipulations

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