Given an integer n
, return true
if it is a power of three. Otherwise, return false
.
An integer n
is a power of three, if there exists an integer x
such that n == 3x
.
Example 1:
Input: n = 27 Output: true Explanation: 27 = 33
Example 2:
Input: n = 0 Output: false Explanation: There is no x where 3x = 0.
Example 3:
Input: n = -1 Output: false Explanation: There is no x where 3x = (-1).
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:
To check if a number is a power of three using brute force, we repeatedly divide the number by 3 until we get 1 or something that is not divisible by 3. If we eventually reach 1, the original number was a power of three.
Here's how the algorithm would work step-by-step:
def is_power_of_three_brute_force(number_to_test):
# Check if the number is valid
if number_to_test <= 0:
return False
while True:
# If the number equals one, it is a power of three
if number_to_test == 1:
return True
# Check if the number is divisible by three
if number_to_test % 3 == 0:
number_to_test = number_to_test / 3
# If not divisible by three, it's not a power of three
else:
return False
The goal is to determine if a given number is a power of three. Instead of repeated division or multiplication, we can leverage the properties of powers of three and integer limits to quickly check if the number is a power of three.
Here's how the algorithm would work step-by-step:
def is_power_of_three(number):
if number <= 0:
return False
largest_power_of_three = 3**19
# Find largest power of 3 within integer limits.
# Check divisibility to determine if it's a power of 3.
if largest_power_of_three % number == 0:
return True
else:
return False
Case | How to Handle |
---|---|
Input is zero | Return false immediately as 3 raised to any integer power is never zero. |
Input is negative | Return false immediately as 3 raised to any integer power is never negative. |
Input is a non-integer | The problem specifies an integer input, so either cast to int (if appropriate) or reject the input if it's non-integral. |
Input is 1 | Return true, as 3 to the power of 0 is 1. |
Input is the maximum integer value | Check if the maximum integer value is a power of three; the iterative approach may take a long time, so a lookup table or modulo operation may be preferred. |
Integer overflow during calculation | If using an iterative or recursive approach, be wary of integer overflow; use a long data type or a modulo operation against a power of 3 to prevent issues. |
Floating-point precision errors | If using logarithms, account for floating point precision errors by allowing a small tolerance when comparing against an integer. |
Input is a large power of 3 that exceeds typical integer limits | Using a precomputed maximum power of 3 within integer bounds helps avoid overflow and reduces computation. |