LeetCode 231. Power of Two

Post by ailswan Oct.26, 2023

231. Power of Two

Problem Statement

link: LeetCode.cn LeetCode

Given an integer n, return true if it is a power of two. Otherwise, return false.

An integer n is a power of two, if there exists an integer x such that n == 2x.

Example:

Input: n = 1 Output: true

Input: n = 16 Output: true

Input: n = 3 Output: false

Solution Approach

Determine if a number is a power of two by repeatedly dividing it by 2.

Algorithm

  1. If the number is less than or equal to 0, return false.
  2. Repeatedly divide the number by 2 as long as it’s evenly divisible.
  3. If the number becomes 1 after divisions, it’s a power of two; otherwise, return false.

Implement

    class Solution:
        def isPowerOfTwo(self, n: int) -> bool:
            if n <= 0:
                return False
            while n > 1:
                if n % 2 == 0:
                    n = n / 2
                else:
                    return False
            return True

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n and not (n & (n - 1))