Leetcode 326. Power of Three

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

1. Description

Power of Three

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
1
2
3
4
5
6
7
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
1
2
3
4
5
6
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/
如果有收获,可以请我喝杯咖啡!