Power of Four

题目
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

答案

class Solution {
    public boolean isPowerOfFour(int num) {
        // Power of 4 <=> 
        // (1) number of trailing 0's in binary reprensentation is even <=>
        // Binary representation has only one 1 and it's in odd position
        
        // Need to check the above two conditions
        // First, check all 1's in binary representation of num are in odd position
        boolean odd = (num | 0x55555555) == 0x55555555;
        // Second, check binary representation of num has only one 1(Equivalent to num is a power of 2)
        boolean one = num != 0 && (num & (num - 1)) == 0;
        return odd && one;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,222评论 0赞 10
  • Given an integer (signed 32 bits), write a function to ch...
    兰缘小妖阅读 251评论 0赞 0
  • LeetCode题目 题目: Given an integer (signed 32 bits), write a...
    _Xie_阅读 220评论 0赞 1
  • 一场台风拦腰断 自然灾难降身前 没有哭泣没有怨 忍痛找到新生点 不到一年双枝现 齐头并进茂盛繁 生命力旺不惧难 洗...
    神于天圣于地阅读 154评论 0赞 0

友情链接更多精彩内容