您的位置:首页 > 其它

LintCode-O(1) Check Power of 2

2014-12-27 05:13 375 查看
Using O(1) time to check whether an integer n is a power of 2.

Example

For n=4, return true

For n=5, return false

Challenge

O(1) time

Analysis:

Use bit manipulation. Be carefull about the 0 and negtive integer.

Solution:

class Solution {
/*
* @param n: An integer
* @return: True or false
*/
public boolean checkPowerOf2(int n) {
if (n<=0) return false;
boolean res = ((n & (n-1))==0) ? true : false;
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: