Power of Two - Complete Solution Guide
Power of Two is LeetCode problem 231, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 == 2 x . Example 1: Input: n = 1 Output: true Explanation: 2 0 = 1 Example 2: Input: n = 16 Output: true Explanation: 2 4 = 16 Example 3: Input: n = 3 Output: false Constraints: -2 31 <= n <= 2 31 - 1 Follow up: Could you solve it without loops/recursion?
Detailed Explanation
The problem asks whether a given integer `n` is a power of two. This means determining if there exists an integer `x` such that `n = 2<sup>x</sup>`. The input is a single integer `n`, and the output is a boolean value: `true` if `n` is a power of two, and `false` otherwise. The input integer is constrained to be within the range of a 32-bit signed integer.
Solution Approach
The provided solutions leverage the bit manipulation technique. The core idea is that if a number is a power of two, its binary representation will have exactly one bit set to 1. Subtracting 1 from a power of two flips all bits to the right of the single set bit and sets those bits to 1, while the single set bit becomes 0. Performing a bitwise AND between the original number and its predecessor will result in 0 if and only if the original number is a power of two. The solutions also explicitly check if the input number is positive to handle the edge case of negative numbers and zero.
Step-by-Step Algorithm
- Step 1: Check if the input `n` is less than or equal to 0. If so, return `false` because powers of two are always positive.
- Step 2: Perform the bitwise AND operation: `n & (n - 1)`.
- Step 3: Check if the result of Step 2 is equal to 0. If it is, return `true` (it's a power of two); otherwise, return `false`.
Key Insights
- Insight 1: Powers of two in binary representation have only one bit set to 1. For example, 1 (0001), 2 (0010), 4 (0100), 8 (1000), etc.
- Insight 2: The bitwise AND operation (`&`) can be used to efficiently check if only one bit is set. `n & (n - 1)` will be 0 if and only if `n` is a power of two.
- Insight 3: Handling the edge case of negative numbers and zero. Powers of two are always positive.
Complexity Analysis
Time Complexity: O(1)
Space Complexity: O(1)
Topics
This problem involves: Math, Bit Manipulation, Recursion.
Companies
Asked at: Qualcomm, Snap, Wipro, tcs.