342:4的幂

问题描述

给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。

示例

输入: 16
输出: true
输入: 5
输出: false

思路

这道题跟上道简单题解法类似。不唠叨了。直接放AC代码。

方法一

class Solution {
    public boolean isPowerOfFour(int num) {
        if(num == 0){
            return false;
        }
        while(num != 1){
            if(num % 4 != 0){
                return false;
            }
            num/=4;
        }
        return true;
    }
}

方法二

class Solution {
    public boolean isPowerOfFour(int num) {
        if(num == 0){
            return false;
        }else if(num == 1){
            return true;
        }
        return num%4 == 0 && isPowerOfFour(num/4);
    }
}

方法三

class Solution {
    public boolean isPowerOfFour(int num) {
        return Math.log10(num)/Math.log10(4)%1 == 0;
    }
}

方法四

class Solution {
    public boolean isPowerOfFour(int num) {
        return Math.log(num)/Math.log(4)%1 == 0;
    }
}

方法五

class Solution {
    public boolean isPowerOfFour(int num) {
        return Integer.toString(num,4).matches("^10*$");
    }
}
发布了396 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41687289/article/details/104907494