mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 326. Power of Three.md
This commit is contained in:
parent
cde8292958
commit
89fa228cd0
18
326. Power of Three.md
Normal file
18
326. Power of Three.md
Normal file
@ -0,0 +1,18 @@
|
||||
# [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++
|
||||
```
|
||||
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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user