*[Lintcode]O(1) Check Power of 2

来源:互联网 发布:暴雪铁人五项 知乎 编辑:程序博客网 时间:2024/05/29 03:30

Using O(1) time to check whether an integer n is a power of2.


Example

For n=4, return true;

For n=5, return false;

Challenge

O(1) time

若为2的幂次方,则只存在一位为1. 可以1)统计1的个数 2)与n-1做与运算,无相同位即为true

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;    }};


0 0
原创粉丝点击