Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
  • Follow up:
Could you solve it without loops/recursion?
  • Examples:
Given num = 16, return true. Given num = 5, return false.
  • Analysis:
num > 0 and (num & (num - 1) == 0) and ((num - 1) % 3 == 0)
  • Code - Java:
class Solution {
    public boolean isPowerOfFour(int num) {
        int temp = num - 1;
        return num > 0 && (num & temp) == 0 && (temp) % 3 == 0;
    }
}
  • Code - C++:
class Solution {
public:
    bool isPowerOfFour(int num) {
        int temp = num - 1;
        return num > 0 && (num & temp) == 0 && (temp) % 3 == 0;
    }
};
  • Code - Python:
class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        temp = num - 1
        return num > 0 and (num & temp) == 0 and (temp % 3 == 0)
  • Code - C:
bool isPowerOfFour(int num) {
    int temp = num - 1;
    return num > 0 && (num & temp) == 0 && (temp) % 3 == 0;
}

results matching ""

    No results matching ""