leetcode 3的幂 (java实现)

    84 ms的普通解法,最先想到:

class Solution {
    public boolean isPowerOfThree(int n) {
        if (n == 1) return true;
        if (n < 3) return false;
        while (n % 3 == 0) {
            if (n == 3) return true;
            n = n / 3;
        }
        return false;
    }
}

    111 ms,我想试一下自带的函数,发现最后会超出 231-1=2147483647 的上线,所以加了判断,而且时间也过长。

class Solution {
    public boolean isPowerOfThree(int n) {
        for (int i = 0; ; i ++) {
            int num = (int)Math.pow(3, i);
            if (num < n) continue;
            if (num == n && num < 2147483647) return true;
            if (num > n || num == 2147483647) return false;
        }
    }
}

    最快的13ms的解法是,int的范围是0-231,在此范围中允许的最大数为319=1162261467,返回值为这个数能否被n整除。

class Solution {
    public boolean isPowerOfThree(int n) {
        return (n > 0) && (1162261467 % n == 0);
    }
}
发布了27 篇原创文章 · 获赞 10 · 访问量 5034

猜你喜欢

转载自blog.csdn.net/l1l1l1l/article/details/88959850
今日推荐