C++ solution no loop / recursion


  • 24
    bool isPowerOfThree(int n) {
            if (n<=0) return false;
            int t = pow(3,(int)(log(INT_MAX)/log(3)));
            return (t%n == 0);
        }
    

    t is maximum power of three


  • 0
    P

    Can you please explain the logic.??


  • 0
    R

    since 3 is prime, it can only be factored as multiples of 3, hence this solution works (get the factor 3^k and then check if its same as n)..for other numbers it won't work.


  • 1
    D

    @piyush31 It finds the largest power of 3 less than INT_MAX first, and then checks if it is divisible by n. log(INT_MAX)/log(3) equals to log3(INT_MAX)


  • 0
    U

    here we need to add a statment that has int64_t .

    class Solution {
    public:
    bool isPowerOfThree(int n)
    {
    int64_t m=n;
    if (m<=0) return false;
    int t = pow(3,(int)(log(INT_MAX)/log(3)));
    return (t%m == 0);

    }
    

    };


Log in to reply
 

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