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

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/d3ef97cc7087
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞