[leetcode] 326. Power of Three 解题报告

题目链接:https://leetcode.com/problems/power-of-three/

Given an integer, write a function to determine if it is a power of three.

Follow up:
Could you do it without using any loop / recursion?


思路:让求一个数是不是3的幂,然后还不让循环,这就是纯数学题了,没意思。

两种代码如下:

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n <= 0) return false;
        while(n != 1)
        {
            if(n%3 != 0)
            {
                cout <<n << " "<< n%3 << endl;
                return false;
            }
            n = n/3;
        }
        return true;
    }
};


数学方法:

class Solution {
public:
    bool isPowerOfThree(int n) {
        return n>0?!(1162261467 % n):0;
    }
};



你可能感兴趣的:(Math,LeetCode)