Version I - basic

Mistakes

Corner cases!

  • n = 0 => false
  • n = 1 => true
public class Solution {
    public boolean isPowerOfThree(int n) {
        if (n < 1) return false;
        while (n > 1) {
            if (n % 3 != 0) {
                return false;
            }
            n /= 3;
        }

        return true;
    }
}

Version II - optimize while loop

Mistakes

Corner cases!

  • n = 0, 不判断的话就变成死循环了
public class Solution {
    public boolean isPowerOfThree(int n) {
        if (n == 0) return false;
        while (n % 3 == 0) {
            n /= 3;
        }

        return n == 1;
    }
}

Version III - Recursion

public class Solution {
    public boolean isPowerOfThree(int n) {
        if (n == 1) return true;
        return n > 0 && (n % 3 == 0) && isPowerOfThree(n / 3);
    }
}

Version IV - Clever

find the largest number that is a power of 3, and check whether it is a multiple of the given input

public class Solution {
    public boolean isPowerOfThree(int n) {
        return n > 0 && Math.pow(3, 19) % n == 0;
    }
}

results matching ""

    No results matching ""