[recommend for beginners]clean C++ implementation with the key math formulation


  • 2

    After seeing others post, I get the key point to one line code is the following math formulation:

    log(b, x) = log(k, x) / log(k, b)

    class Solution {
    public:
        bool isPowerOfThree_1(int n) {
           return n>0 && (n==1 || (n%3==0 && isPowerOfThree(n/3))); 
        }
        
        bool isPowerOfThree_2(int n) {
           if(n>1)
                while(!n%3) n/=3;
           return n==1;
        }
        
        bool isPowerOfThree(int n) {
           //math.log only support base=10 base2 , so to calculate the log_3
           //we use the log10(a)/log10(3)=log3(a)
           int maxPowerOfThree = (int)pow(3, (int)(log(0x7fffffff)/log(3)));
           return n>0 && maxPowerOfThree%n==0;
        }
        
        // bool isPowerOfThree(int n){
        //     return (log(n) / log(3)) % 1==0;
        // }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.