PU Power of Three

Jan 01, 1970

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?

C Solution 1:

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

C Solution 2:

// Maybe better, but not portable.
bool isPowerOfThree(int n) {
    return n > 0 && 1162261467 % n == 0;
}

C Solution 3:

bool isPowerOfThree(int n) {
    int limit = (int) pow(3, (int)(log(INT_MAX) / log(3)));
    return n > 0 && limit % n == 0;
}

Summary:

  1. The first and second: 55ms, 24.48%, The third: 49ms, 47.92%. Yes, make no sence.
  2. The third should be perfect, could be, maybe.

LeetCode: 326. Power of Three