2019.9.26 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
智力题,在不使用循环和递归的情况下有三种方法:
1.进制转换:换为3进制数,且字符串满足最高位为1其余为0。
2.换底公式:用%1判断log3(n)是否为整数。
3.最大指数:int型中3的幂最大值为19,对应数字为1162261467
Given an integer, write a function to determine if it is a power of three.
给定一个整数,写一个函数来判断它是否是 3 的幂次方。
示例 1:
输入: 27
输出: true
示例 2:
输入: 0
输出: false
示例 3:
输入: 9
输出: true
示例 4:
输入: 45
输出: false
进阶:
你能不使用循环或者递归来完成本题吗?
/**
*
* Given an integer, write a function to determine if it is a power of three.
* 给定一个整数,写一个函数来判断它是否是 3 的幂次方。
*
*/
public class PowerOfThree {
//进制转换:换为3进制数,且字符串满足最高位为1其余为0
public boolean isPowerOfThree(int n) {
return Integer.toString(n, 3).matches("^10*$");
}
//换底公式:用%1判断log3(n)是否为整数
public boolean isPowerOfThree2(int n){
//用log代替log10会产生double精度误差
//return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;
return (Math.log10(n) / Math.log10(3)) % 1 == 0;
}
//最大指数:int型中3的幂最大值为19,对应数字为1162261467
public boolean isPowerOfThree3(int n) {
return n > 0 && 1162261467 % n == 0;
}
}
#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#