-
Notifications
You must be signed in to change notification settings - Fork 0
/
power_of_three.cpp
50 lines (45 loc) · 930 Bytes
/
power_of_three.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 326. Power of Three: https://leetcode.com/problems/power-of-three
// Author: [email protected]
#include <stdio.h>
#include <stdlib.h>
// Iterative loop
class Solution1
{
public:
bool isPowerOfThree(int n)
{
if (n < 1)
{
return false;
}
while ((n % 3) == 0)
{
n /= 3;
}
return (n == 1);
}
};
// Integer limitation trick
class Solution2
{
public:
bool isPowerOfThree(int n)
{
// 3**19 = 1162261467 is smaller than INT_MAX
// 3**20 is bigger than INT_MAX
return (n > 0 && (1162261467 % n) == 0);
}
};
using Solution = Solution2;
int main(int argc, char* argv[])
{
int n = 27;
if (argc > 1)
{
n = atoi(argv[1]);
}
bool is_power = Solution().isPowerOfThree(n);
printf("Input: %d\n", n);
printf("Output: %s\n", (is_power ? "true" : "false"));
return 0;
}