[Lintcode]142. O(1) Check Power of 2

142. O(1) Check Power of 2

  • 本题难度: Easy
  • Topic: Math&Bit Manipulation

    Description

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

Example
Example 1:
Input: 4
Output: true

Example 2:
Input: 5
Output: false

Challenge
O(1) time

别人的代码 参考野球拳刷刷刷LeetCode LintCode 解题报告

class Solution {
    /*
     * @param n: An integer
     * @return: True or false
     */
    public boolean checkPowerOf2(int n) {
        // write your code here
        return n > 0 && (n & (n - 1)) == 0;
    }
}

思路

没想到合适的方法。不太会做这类的题

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10358610.html
今日推荐