class Solution:
def checkPowersOfThree(self, n: int) -> bool:
# Repeatedly check the remainder when dividing by 3
while n > 0:
if n % 3 == 2:
return False
n //= 3
return True
class Solution {
public:
bool checkPowersOfThree(int n) {
while (n > 0) {
if (n % 3 == 2) return false;
n /= 3;
}
return true;
}
};
class Solution {
public boolean checkPowersOfThree(int n) {
while (n > 0) {
if (n % 3 == 2) return false;
n /= 3;
}
return true;
}
}
var checkPowersOfThree = function(n) {
while (n > 0) {
if (n % 3 === 2) return false;
n = Math.floor(n / 3);
}
return true;
};
Given an integer n
, determine if it can be expressed as the sum of distinct powers of three. In other words, can you write n
as 3^0 + 3^1 + ... + 3^k
for some set of non-repeating exponents?
true
if such a representation is possible, and false
otherwise.n
≤ 107
At first glance, this task seems similar to the "subset sum" problem: can we pick a subset of powers of three that adds up to n
? A brute-force approach might try all combinations of powers of three up to n
, but this quickly becomes inefficient as n
grows.
However, there's a key insight: every number can be represented in base 3, just like binary (base 2) for powers of two. If n
can be written as a sum of distinct powers of three, then its base-3 representation should only contain digits 0 or 1 (not 2). If a digit "2" appears, it would mean we need to use the same power of three twice, which isn't allowed.
This observation allows us to check the base-3 digits of n
efficiently, rather than checking all possible subsets.
To determine if n
is a sum of distinct powers of three, we use the following algorithm:
n
by 3 repeatedly: At each step, check the remainder (n % 3
).n
can't be made from distinct powers of three. Return false
.n
by 3 and repeat the process.n
reaches 0: All digits were 0 or 1, so n
can be written as the sum of distinct powers of three. Return true
.
This method is efficient because it only requires checking the digits of n
in base 3, which takes O(log3(n)) steps.
Example: Let n = 91
91 % 3 = 1
(OK)91 // 3 = 30
30 % 3 = 0
(OK)30 // 3 = 10
10 % 3 = 1
(OK)10 // 3 = 3
3 % 3 = 0
(OK)3 // 3 = 1
1 % 3 = 1
(OK)1 // 3 = 0
(done)91
can be written as a sum of distinct powers of three.
n = 21
21
cannot be written as a sum of distinct powers of three.
Brute-force Approach:
n
, which is exponential in the number of powers (O(2k)).n
.n
by a factor of 3, so we perform O(log3(n)) steps.The key insight to this problem is recognizing the connection to base-3 representation. If a number's base-3 digits are all 0 or 1, it can be written as a sum of distinct powers of three. This allows us to check the condition efficiently, without needing to try all possible combinations. The approach is elegant, fast, and leverages number representation theory for an optimal solution.