Skip to content

342. Power of Four

https://leetcode.com/problems/power-of-four/

js
/**
 * @param {number} num
 * @return {boolean}
 */
var isPowerOfFour = function(num) {
  if (num < 1) {
    return false
  }
  if (num === 1) {
    return true
  }
  return num % 4 === 0 && isPowerOfFour(num / 4)
}

/**
 * @param {number} num
 * @return {boolean}
 */
var isPowerOfFour2 = function(num) {
  if (num < 1) {
    return false
  }
  while (num % 4 === 0) {
    num /= 4
  }
  return num === 1
}

/**
 * @param {number} num
 * @return {boolean}
 */
var isPowerOfFour3 = function(num) {
  const str = num.toString(2)
  return str[0] === '1' &&
    str.length % 2 == 1 &&
    str.slice(1).split('').every(b => b === '0')
}
py
class Solution:

    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num < 1:
            return False
        if num == 1:
            return True
        return num % 4 == 0 and self.isPowerOfFour(num / 4)

    def isPowerOfFour2(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num < 1:
            return False
        while num % 4 == 0:
            num = num / 4
        return num == 1

    def isPowerOfFour2(self, num):
        """
        :type num: int
        :rtype: bool
        """
        s = bin(num)[2:]
        return s[0] == '1' and len(s) % 2 == 1 and all([c == '0' for c in s[1:]])