问题描述
给定一个整数 (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*$");
}
}