美文网首页
[LeetCode 326] Power of Three

[LeetCode 326] Power of Three

作者: 酸辣粉_2329 | 来源:发表于2017-02-08 03:29 被阅读0次

传入一个整数n,判断它是不是3的次方数。


暴力:

循环或者递归(递归还得用空间)

    public boolean isPowerOfThree(int n) {
        if (n == 1) {
            return true;
        }
        if (n < 3) {
            return false;
        }
        // int 除法会舍去除不尽的,除不尽就被当作除尽了
        double num = n * 1.0; 
        while (num > 3) {
            num = num / 3;
        }
        if (num % 3 != 0) {
            return false;
        } else {
            return true;
        }
    }

牛逼且能看懂的方法:(O(1)时间)

3^19 = 1162261467
3^20 = 3486784401 (超出了int的范围)

    public boolean isPowerOfThree(int n) {
        if (n < 0) {
            return false;
        }
        double MAX = Math.pow(3, 19);
        return MAX % n == 0;
    }

其他的方法根本看不懂,数学太差,但是还是放上来,作为以后学习用
链接:https://discuss.leetcode.com/topic/33536/a-summary-of-all-solutions-new-method-included-at-15-30pm-jan-8th/2

public boolean isPowerOfThree(int n) {
    return (Math.log10(n) / Math.log10(3)) % 1 == 0;
}

相关文章

网友评论

      本文标题:[LeetCode 326] Power of Three

      本文链接:https://www.haomeiwen.com/subject/jiqvittx.html