Leetcode - Power of Four

My code:

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

reference:
https://discuss.leetcode.com/topic/42860/java-1-line-cheating-for-the-purpose-of-not-using-loops

Good solution without good explanation,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!

Anyway, Good luck, Richardo! -- 10/14/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,426评论 0 23
  • 是不是所有的青春,都是一场盛大的梦境,
    隔壁小占阅读 1,014评论 0 1
  • 我时常忆起 那行将枯萎的青春 犹如深秋的落叶 在岁月的记忆里拾起 已是片片斑驳 曾经的曾经哪曾想 这消逝的年轮 会...
    榆之木阅读 728评论 0 0
  • 十几岁二十几岁的我们正值青春,觉得生离死别离我们那么远。殊不知,上天有时候就会跟我们开这样的玩笑,让你承受你之前觉...
    Ice万阅读 962评论 0 0
  • 一般情况下,如果有些代码必须在项目启动的时候就执行的时候,需要使用静态代码块,这种代码是主动执行的;需要在项目启动...
    Ten_Minutes阅读 1,885评论 0 3