Skip to content

Latest commit

 

History

History
18 lines (18 loc) · 1020 Bytes

326. Power of Three.md

File metadata and controls

18 lines (18 loc) · 1020 Bytes

思路

题目求给定数是否是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..)的幂的问题!!!
更多解法参考此处

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;
    }
};