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 1:
Input: n = 1 Output: true Explanation: 20 = 1
Example 2:
Input: n = 16 Output: true Explanation: 24 = 16
Example 3:
Input: n = 3 Output: false
Constraints:
-231 <= n <= 231 - 1
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to checking if a number is a power of two involves testing different powers of two. We essentially keep multiplying 2 by itself and see if we ever reach the target number. If we do, it's a power of two; if we pass it, it's not.
Here's how the algorithm would work step-by-step:
def is_power_of_two_brute_force(number):
power_of_two = 1
# Start with 2^0 = 1
while True:
if power_of_two == number:
# We found the number so it is a power of two
return True
if power_of_two > number:
# The power of two is greater than input
return False
# Multiply the power of two by two
power_of_two *= 2
The trick to this problem is understanding how numbers that are powers of two are represented in binary. We can then use a bitwise operation to quickly check if a number is a power of two without repeatedly dividing or using logarithms.
Here's how the algorithm would work step-by-step:
def is_power_of_two(number):
if number <= 0:
return False
# Subtract 1 from the number.
number_minus_one = number - 1
# Perform a bitwise AND to check power of 2.
bitwise_and_result = number & number_minus_one
# If the result is 0, it's a power of 2.
if bitwise_and_result == 0:
return True
else:
return False
Case | How to Handle |
---|---|
Input is zero | Return false because zero is not a power of two. |
Input is a negative number | Return false because negative numbers are not powers of two. |
Input is one | Return true because 2^0 = 1, so 1 is a power of two. |
Input is a large positive integer (potential overflow) | Ensure the algorithm avoids potential integer overflows by using appropriate data types or bitwise operations (e.g., n > 0 && (n & (n - 1)) == 0). |
Input is a very small positive number close to zero (potential floating-point errors if logarithms are used) | Avoid using logarithms to prevent potential floating-point inaccuracies. |
Maximum integer value (Integer.MAX_VALUE) | Check if Integer.MAX_VALUE is a power of 2 and return true if it is, false otherwise. |
Input is a non-integer | The problem specifies an integer input; handle this by either casting the input to an integer and proceeding, or throwing an IllegalArgumentException. |
Multiple of a power of two, but not a power of two itself (e.g. 6) | The bitwise operation `n & (n - 1)` correctly identifies if a number is not a power of two. |