Power of Two

Problem: Power of Two

It's a classic bit manipulation problem so just remember it.

Code in Python:

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return bool(n > 0 and not (n & (n - 1)))

If a number is power of two, its bit format must be 100...00. If we minus it with 1, we can get 111...111. If we AND these two numbers, we can get all zero. Care for the situation that n = 0.

For other classic bit manipulation, please refer to Bit Manipulation Tutorial, or do your own searching with Google.

results matching ""

    No results matching ""