LeetCode/solutions/326. Power of Three.md
2019-09-13 23:08:41 +08:00

19 lines
1020 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [326. Power of Three](https://leetcode.com/problems/power-of-three/description/)
# 思路
题目求给定数是否是3的幂。而且要求不能运用循环和递归。
由于3是质数所以若对n进行质因子分解可以得到3^k的形式则是3的幂。因此用一个很大的3的幂(3^M)除以n
若能除进,即3^M = m * n则n是3的幂(因为3^M分解因子只能是3^x形式)否则则不是。很大的3的幂可以设置成int型不溢出的最大的3的幂。
**以上方法适用于判断某数是否是某个质数(如2、3、5..)的幂的问题!!!**
更多解法参考[此处](https://leetcode.com/problems/power-of-three/discuss/77876/**-A-summary-of-all-solutions-(new-method-included-at-15:30pm-Jan-8th))
# C++
```C++
class Solution {
public:
bool isPowerOfThree(int n) {
// int maxPowerOf3 = (int)pow(3, (int)(log(INT_MAX) / log(3))); // = 1162261467;
int maxPowerOf3 = 1162261467;
return n > 0 && maxPowerOf3 % n == 0;
}
};
```