码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 14 - Power of three; Math; Integer; Digit;

时间:2016-01-15 06:28:22      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:

No loop; No recursion; 我没找到规律 但是从讨论区看到别人的思路:

If N is a power of 3:

  • It follows that 3^X == N
  • It follows that log (3^X) == log N
  • It follows that X log 3 == log N
  • It follows that X == (log N) / (log 3)
  • For the basis to hold, X must be an integer.

代码:

public class Solution {
    public boolean isPowerOfThree(int n) {
        double diff = 10e-15;
        double x = Math.log(n)/Math.log(3);
        return Math.abs( x - Math.round(x)) <= diff;
    }
}

  

Jan 14 - Power of three; Math; Integer; Digit;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5132198.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!