美文网首页Leetcode
Leetcode.326.Power of Three

Leetcode.326.Power of Three

作者: Jimmy木 | 来源:发表于2019-12-18 12:39 被阅读0次

题目

给定一个数,判断是否是3的n次方。不要用循环和递归。

Input:4782968
Output:false
Input:27
Output:true
Input:45
Output:false

思路

最简单容易理解的方法就是找出最大的3的n次方,然后除以x。

bool isPowerOfThree2(int n) {
    // 3的19次方
    return n > 0 && 1162261467 % n == 0;
}

总结

比较奇怪的题目,还有使用log(n)/log(3)的方法,但是精度有问题。

相关文章

网友评论

    本文标题:Leetcode.326.Power of Three

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