# 342. Power of Four 4的幂

@TOC

[LeetCode]

Total Accepted: 9305 Total Submissions: 28083 Difficulty: Easy

## # 题目描述

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example 1:

``````Input: 16
Output: true
``````

Example 2:

``````Input: 5
Output: false
``````

Follow up: Could you solve it without loops/recursion?

## # 解题方法

### # 递归

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

AC:2ms

### # 迭代

``````class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0: return False
while num % 4 == 0:
num /= 4
return num == 1
``````

### # 位运算

``````class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
return num > 0 and (num & (num - 1)) == 0 and (num & 0x55555555) != 0
``````

Java代码如下：

``````public class Solution {
public boolean isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) ==0  && (num & 0x55555555) !=0;
}
}
``````

### # 函数法

``````class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
return num > 0 and (4 ** (int(math.log(num, 4)))) == num
``````

## # 日期

2016/5/1 17:36:06 2018 年 11 月 22 日 —— 感恩节快乐~