码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Power of Four

时间:2016-11-23 12:51:02      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:isp   could   log   turn   bool   with   should   sig   tco   

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 }

 

Leetcode: Power of Four

标签:isp   could   log   turn   bool   with   should   sig   tco   

原文地址:http://www.cnblogs.com/EdwardLiu/p/6093073.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!