您的位置:首页 > 编程语言 > Java开发

Leetcode:326. Power of Three(JAVA)

2016-03-03 16:51 309 查看
【题目描述】

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?
【思路】
不用循环和递归,则:

3^x=n

log(3^x) = log(n)

x log(3) = log(n)

x = log(n) / log(3)
由于JAVA double浮点型的问题,需判断Math.abs(x - Math.round(x)) < 10e-15
public class Solution {
public boolean isPowerOfThree(int n) {
double temp = 10e-15;
if(n==0) return false;

double res = Math.log(n) / Math.log(3);
return Math.abs(res-Math.round(res)) < temp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java