LeetCode之342,Power of Four

来源:互联网 发布:java嵌入html5 编辑:程序博客网 时间:2024/06/06 02:11

这个题和Power Of Two有很多相同点,可以在其基础上做适当延伸。


原题:

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?


特别注意上面那个:follow up的内容。


解决用的代码是:

class Solution {public:    bool isPowerOfFour(int num) {        //if 2 or 8,return false        //if 4 or 16,return true        //so 0101 & 1000 =0000        //0101 & 0100 =0100        //get idea above,so        if(num<=0) return false;        return ((num&(num-1))==0 &&(num&0x55555555));    }};


0 0