342. 4的幂

题目描述

给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
示例 1:
输入: 16
输出: true
示例 2:
输入: 5
输出: false
进阶:
你能不使用循环或者递归来完成本题吗?

方法1

class Solution {
public:
    bool isPowerOfFour(int n) {
        
        if(n <= 0)
            return false;
        if( n == 1)
            return true;
        while(n%4 == 0) n /= 4;
        if(n == 1)
            return true;
        else
            return false;
        
    }
};

方法2

所以4的倍数1那位一定是奇数位 0x5=0101,32=4*8

class Solution {
public:
    bool isPowerOfFour(int n) {
        //4^x=2^2x
        if(n <= 0 || (n & (n-1))!=0)
            return false;
        return (n & 0x55555555) !=0;       
    }
};

方法3

4的幂次质因子只有4,而整数范围内的4的幂次最大的数,它一定能够被4的幂次整除

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n <= 0)
            return false;
        if( n == 1)
            return true;
        int theMax = pow(4, int(log(INT_MAX) / log(4)));
        if(theMax%n == 0)
        	return true;
        else
        	return false;        
    }
};

posted on 2021-07-19 22:06  朴素贝叶斯  阅读(39)  评论(0编辑  收藏  举报

导航