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

LeetCode-326. Power of Three

时间:2016-02-18 19:32:21      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

Description:

Given an integer, write a function to determine if it is a power of three.

判断一个整数是否是3的幂。

基于公式log3^n可以得出y=lg(n)/log(3)如果y正好是个整数的话,说明n是3的幂。也可以使用循环除3的方法,也不是很浪费时间循环不了多少次。

public class Solution {
    public boolean isPowerOfThree(int n) {
        
        double ans = Math.log(n) / Math.log(3);
        return Math.abs(ans - Math.round(ans)) < 0.000000000001;
    }
}

技术分享

LeetCode-326. Power of Three

标签:

原文地址:http://www.cnblogs.com/wxisme/p/5199070.html

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