[LeetCode][JavaScript]Power of Three

Power of Three

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?

https://leetcode.com/problems/power-of-three/

 

 


 

 

要求判断一个数是不是3的幂次方。

最直观的做法是不停除以3,看余数是否为零。

题目要求不能用递归和循环,那就是数学题了。

把给定的数N用求以3为底的对数(log3N),如果结果是整数说明N是3的幂次方。

 

1 /**
2  * @param {number} n
3  * @return {boolean}
4  */
5 var isPowerOfThree = function(n) {
6     n = Math.log(n) / Math.log(3);
7     return Math.abs(n - Math.round(n)) < 1e-10 ? true : false;
8 };

 

 

 

posted @ 2016-02-04 11:08  `Liok  阅读(412)  评论(0编辑  收藏  举报