LeetCode题解——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?

Credits:

Special thanks to @dietpepsi for adding this problem and creating all test cases.

class Solution {
public:
    bool isPowerOfThree(int n) {
        if (n <= 0) return 0;
    
        int max_pow3 = log10(INT_MAX)/log10(3); // simple math formula to compute log_3(N)
        int max_pow3_val = pow(3, max_pow3);
    
        return max_pow3_val % n == 0;
    }
};


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