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?
  • Analysis:
loop 

    if n % 3 != 0, return false

    Otherwise, n /= 3, until n < 1, return true
  • Code - Java:
class Solution {
    public boolean isPowerOfThree(int n) {
        if (n <= 0) {
            return false;
        }
        while (n > 1) {
            if (n % 3 != 0) {
                return false;
            }
            n /= 3;
        }
        return true;
    }
}
  • Code - C++:
class Solution {
public:
    bool isPowerOfThree(int n) {
        if (n <= 0) {
            return false;
        }
        while (n > 1) {
            if (n % 3 != 0) {
                return false;
            }
            n /= 3;
        }
        return true;
    }
};
  • Code - Python:
class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False
        while n > 1:
            if n % 3 != 0:
                return False
            n /= 3
        return True
  • Code - C:
bool isPowerOfThree(int n) {
    if (n <= 0) {
        return false;
    }
    while (n > 1) {
        if (n % 3 != 0) {
            return false;
        }
        n /= 3;
    }
    return true;
}

results matching ""

    No results matching ""