Leetcode 326. Power of Three

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82390263

文章作者: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/

猜你喜欢

转载自blog.csdn.net/Quincuntial/article/details/82390263