首页 > 其他 > 详细

[LeetCode] Power of Four

时间:2016-05-16 11:07:57      阅读:253      评论:0      收藏:0      [点我收藏+]

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

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

解题思路

如果一个数为4n,则它等于n个4相乘。乘以4可以化为左移2位的位运算,因此4n规律如下:

0000000000000001
0000000000000100
0000000000010000
0000000001000000
0000000100000000

二进制表示中仅有一个1,且1位于奇数位处。
可将此题与 Power of Two进行类比,主要区别在于判断等于1的位是否位于奇数位处。

实现代码

// Runtime: 2 ms
public class Solution {
    public boolean isPowerOfFour(int num) {
        return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0 ; 
    }
}

[LeetCode] Power of Four

原文:http://blog.csdn.net/foreverling/article/details/51422916

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!