Leetcode 231: Power of Two

grid47
grid47
Exploring patterns and algorithms
Oct 14, 2024 4 min read

A series of glowing numbers doubling, each number expanding into the next power of two.
Solution to LeetCode 231: Power of Two Problem

Given an integer n, determine if it is a power of two. An integer n is considered a power of two if there exists an integer x such that n == 2^x.
Problem
Approach
Steps
Complexity
Input: The input consists of a single integer n (−2^31 <= n <= 2^31 − 1).
Example: Input: n = 8
Constraints:
• -2^31 <= n <= 2^31 - 1
Output: Return true if n is a power of two, otherwise return false.
Example: Output: true
Constraints:
Goal: The goal is to verify whether the number n is a power of two using bit manipulation.
Steps:
• Check if n is less than or equal to zero, in which case it is not a power of two.
• Perform a bitwise AND operation between n and (n - 1). If the result is zero, then n is a power of two.
Goal: The input integer n must lie within the range of a 32-bit signed integer.
Steps:
Assumptions:
• The input will be a valid integer within the specified range.
• n may be negative or zero, but only positive values can be a power of two.
Input: Input: n = 8
Explanation: Since 8 can be written as 2^3, it is a power of two. Thus, the output is true.

Input: Input: n = 5
Explanation: 5 cannot be written as 2^x for any integer x, so the output is false.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus