卖萌的弱渣

I am stupid, I am hungry.

Check Power of Two

Check Power of Two

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

Solution

  • Time: O(1)

    if x & (x-1) == 0, then x is the power of 2

(Check-Power-of-Two.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
    #
    # @param n: An integer
    # @return: True or false
    #
    # if x & x-1 == 0, then x is the power of 2
    def checkPowerOf2(self, n):
        if n < 1:
            return False
        if (n & (n-1)) == 0:
            return True
        else:
            return False