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?

Solution: Loop

    bool isPowerOfThree(int n) {
        while (n && n % 3 == 0) {
            n /= 3;
        }
        return n == 1;
    }

Solution:

    bool isPowerOfThree(int n) {
        return fmod(log10(n)/log10(3), 1)==0;
    }

results matching ""

    No results matching ""