342. Power of Four

来源:互联网 发布:qt 调用dotnet 编程 编辑:程序博客网 时间:2024/06/03 18:16

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?


只有最高位为1,最高位后面是偶数个0

num-1如果后面全是1,那就一定是3的倍数


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