Leetcode: Power of Four

发布时间:2017-3-2 3:59:01 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"Leetcode: Power of Four ",主要涉及到Leetcode: Power of Four 方面的内容,对于Leetcode: Power of Four 感兴趣的同学可以参考一下。

1 Given an integer (signed 32 bits), write a function to check whether it is a power of 4.2 3 Example:4 Given num = 16, return true. Given num = 5, return false.5 6 Follow up: Could you solve it without loops/recursion?

it's easy to find that power of 4 numbers have those 3 common features.

First,greater than 0.

Second,only have one '1' bit in their binary notation,so we use x&(x-1) to delete the lowest '1',and if then it becomes 0,it prove that there is only one '1' bit.

Third,the only '1' bit should be locate at the odd location,for example,16.It's binary is 00010000.So we can use '0x55555555' to check if the '1' bit is in the right place.With this thought we can code it out easily!

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

上一篇:处理数据队列
下一篇:ubuntu 安装时遇到 hash sum mismatch 处理方法

相关文章

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。