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

本文介绍了一种使用位操作的方法来判断一个32位带符号整数是否为4的幂。通过排除负数和0,并利用位运算判断是否为2的幂,最后验证该数减1后能否被3整除。

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 算法题目列表 - LeetCode Algorithms Questions List

转载于:https://www.cnblogs.com/jimmycheng/p/7082982.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值