Check if Number is a Sum of Powers of Three
You want to determine if an integer ( n ) can be represented as the sum of distinct powers of three.
We can approach this problem by expressing ( n ) in base 3 and then checking if any digit in the base-3 representation is greater than 1. If there’s a digit greater than 1, then it means that the sum includes two or more of the same power of three, and the answer should be false. If all digits are 0 or 1, it means that the sum only includes distinct powers of three, and the answer should be true.
Here’s the code:
|
|
Explanation:
- If the remainder of
n
divided by 3 is 2, it means that the number cannot be represented as the sum of distinct powers of three, and we return False. - Otherwise, we continue to divide
n
by 3 untiln
becomes 0. - If we reach
n = 0
without finding any remainder of 2, it means thatn
can be represented as the sum of distinct powers of three, and we return True.
Examples:
- For
n = 12
, the base-3 representation is “110”, so the output is True. - For
n = 91
, the base-3 representation is “10101”, so the output is True. - For
n = 21
, the base-3 representation is “210”, so the output is False.