首页 > 代码库 > LeetCode 342. Power of Four (4的次方)

LeetCode 342. Power of Four (4的次方)

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

Example:
Given num = 16, return true. Given num = 5, return false.

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

 


题目标签:Bit Manipulation

  这道题目让我们判断一个数字是不是4的次方数,首先排除负数和0。然后利用2的次方数特性,如果 num & (num-1) == 0 的话,那么这个数字是2的次方数 (基于2进制原理)。利用这一点,排除所有不是2的次方数。最后,如果一个数字是4的次方数,那么这个数字 -1 一定可以被3整除。排除掉数字 -1不能被3整除的,剩下的就是4的次方数

 

Java Solution:

Runtime beats 24.44% 

完成日期:06/26/2017

关键词:Bit Manipulation

关键点:基于 num & (num-1) 来判断是不是2的次方数

 

 1 public class Solution 
 2 {
 3     public boolean isPowerOfFour(int num) 
 4     {
 5         if(num <= 0) // if num is 0 or negative number
 6             return false;
 7         
 8         if((num & (num - 1)) != 0) // if num is not the power of 2
 9             return false;
10         
11         if((num - 1) % 3 != 0) // if num - 1 cannot be divided by 3 
12             return false;
13         
14         return true;
15     }
16 }

参考资料:

http://www.cnblogs.com/grandyang/p/5403783.html

 

LeetCode 342. Power of Four (4的次方)