LeetCode - 326. Power of Three

topic

LeetCode - 326. Power of Three

Topic Link

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

Reference blog
Problem-solving ideas

Solution twenty-one start intend to use $ 3 ^ {log_3N} == N $, determines whether a power of 3, is utilized after rounding to the end, and then restored. However, pow arithmetic, floating point arithmetic, and log time, there will be loss of precision. C language number is the log base e, serious loss of precision when calculating the recommended number of base 10 to log10.

Problem-solving Source
  1. A Solution
1
2
3
4
5
6
7
8
9
10
class  {
public:
bool isPowerOfThree(int大专栏  LeetCode - 326. Power of Threepan> n) {
long long int a = 1;
while(a < n){
a *= 3;
}
return a == n;
}
};
  1. Solution two
1
2
3
4
5
6
class  {
public:
bool isPowerOfThree(int n) {
return (n > 0 && log10(n)/log10(3) == int(log10(n)/log10(3)));
}
};

Guess you like

Origin www.cnblogs.com/dajunjun/p/11711047.html