326. Power of Three
2016-02-25 19:46
441 查看
题目:
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
思路:
题目的关键在于不使用循环和递归,想了很久也没有想到合适的,看了discuss之后才知道是一个数学问题,好吧,我承认自己忘记对数了。。。
代码如下:
public class Solution {
public boolean isPowerOfThree(int n) {
if(n < 1){return false;}
// Math.log(n) / Math.log(3)会出错,Math.log是以e为底的
double res = Math.log10(n) / Math.log10(3);
if(res%1 == 0){
return true;
}else{
return false;
}
}
}
【注】
不明白为什么使用Math.log会出错。。。求解答。。。
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
思路:
题目的关键在于不使用循环和递归,想了很久也没有想到合适的,看了discuss之后才知道是一个数学问题,好吧,我承认自己忘记对数了。。。
代码如下:
public class Solution {
public boolean isPowerOfThree(int n) {
if(n < 1){return false;}
// Math.log(n) / Math.log(3)会出错,Math.log是以e为底的
double res = Math.log10(n) / Math.log10(3);
if(res%1 == 0){
return true;
}else{
return false;
}
}
}
【注】
不明白为什么使用Math.log会出错。。。求解答。。。
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树