您的位置:首页 > 其它

LeetCode -- Power of Three

2016-02-13 10:17 393 查看
Question:

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?

Analysis:

给出一个整数,写一个函数判断它是否是3的n次幂。

注意:能否不用循环或递归解决这个问题?

Solution1: Using Loop.

//Solution1: Loop
public boolean isPowerOfThree(int n) {
if(n <= 0)
return false;
while(n > 1) {
if(n % 3 != 0)
break;
else
n /= 3;
}
return n == 1;
}


Solution2: Using Recursion.

//Solution2: Recursion.
public static boolean isPowerOfThree(int n) {
if(n <= 0)
return false;
if(n == 1)
return true;
if(n % 3 == 0)
return isPowerOfThree(n/3);
else return false;
}


Solution3: Using Log Function. (logab = logcb / logca)

public boolean isPowerOfThree(int n) {
if(n <= 0)
return false;
double log = Math.log10(n) / Math.log10(3);
if(log - (int)log == 0)
return true;
else return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: