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

Leetcode 326. Power of Three

作者: SnailTyan | 来源:发表于2018-09-04 21:00 被阅读5次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Power of Three

    2. Solution

    • Version 1
    class Solution {
    public:
        bool isPowerOfThree(int n) {
            if(n <= 0) {
                return false;
            }
            while(n != 1) {
                if(n % 3) {
                   return false; 
                }
                n /= 3;
            }
            return true; 
        }
    };
    
    • Version 2
    class Solution {
    public:
        bool isPowerOfThree(int n) {
            // 1162261467 is 3^19,  3^20 is bigger than int 
            return ((n > 0) && (1162261467 % n == 0));
        }
    };
    
    • Version 3
    class Solution {
    public:
        bool isPowerOfThree(int n) {
            return fmod(log10(n) / log10(3), 1) == 0;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/power-of-three/description/

    相关文章

      网友评论

        本文标题:Leetcode 326. Power of Three

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