C++ math solution without loop or recursion (with math explanation)

  • 4

    Here is the math:
    log(n) / log(3) <==> log(3)^x / log(3) for n == 3 ^ x, and x is integer.
    Use log formula to bring x to front, we have x*log(3) / log(3), which is equal to x.
    We only need to check if x is an whole number by using floor(x) == x

    class Solution {
        bool isPowerOfThree(int n) {
            if(n == 0) return false;
            double x = log10(n) / log10(3);
            return floor(x) == x;

  • 0

    Do you happen to know why it's false if I use log() instead of log10() that you used? Thanks!

  • 1

    it may be solved by following:
    double x = log(n)/log(3);

        double delta = 0.00000000001;
        if(abs(x-floor(x))<delta || abs(x-floor(x)) > (1-delta)){
            return true;

  • 0
    This post is deleted!

  • 0

    Yeah, it's just a problem of precision, just like iamyy's solution suggests.

Log in to reply

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