Power of Three

2019-05-25 22:47:50 浏览数 (1)

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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
代码语言:javascript复制
class Solution {
public:
    bool isPowerOfThree(int n) {
        return fmod(log10(n) / log10(3), 1) == 0;
    }
};

0 人点赞