Given an integer (signed 32 bits), write afunction 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 withoutloops/recursion?
谷歌翻译:给定一个整数(带符号的32位),写一个函数来检查它是否为4的幂。例:给定num = 16,返回true。 给定num = 5,返回false。跟进:你能解决它没有循环/递归?
这题考的比较基础,就是判断两个类型不一致的数完全相等,防止类型转换导致精度缺失,而结果错误。大家可以记住这个用法,还是很有用的。以前比赛考试的时候也经常用到过。代码如下:
public class Solution {
public boolean isPowerOfFour(int num) {
double res=Math.log(num)/Math.log(4);
return (Math.abs(res-Math.rint(res))< 0.0000000001);
}
}