LeetCode - 326. Power of Three

题目

LeetCode - 326. Power of Three

题目链接

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

参考博客
解题思路

解法二一开始打算使用$3^{log_3N}== N$,来判断是否是3的幂,利用的是取整后去尾,再还原。但是pow运算,和log运算时浮点运算,会有精度丢失。C语言中log是以e为底的对数,计算时精度丢失严重,建议用以10为底的对数log10.

解题源码
  1. 解法一
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. 解法二
1
2
3
4
5
6
class  {
public:
bool isPowerOfThree(int n) {
return (n > 0 && log10(n)/log10(3) == int(log10(n)/log10(3)));
}
};

猜你喜欢

转载自www.cnblogs.com/dajunjun/p/11711047.html