码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode-O(1) Check Power of 2

时间:2014-12-27 06:44:21      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

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:

 1 class Solution {
 2     /*
 3      * @param n: An integer
 4      * @return: True or false
 5      */
 6     public boolean checkPowerOf2(int n) {
 7         if (n<=0) return false;
 8         boolean res = ((n & (n-1))==0) ? true : false;
 9         return res;
10     }
11 };

 

LintCode-O(1) Check Power of 2

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/4187964.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!