1780. Check if Number is a Sum of Powers of Three #1389
-
Topics: Given an integer An integer Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if a given integer ApproachThe key insight here is to recognize that if a number can be represented as a sum of distinct powers of three, its ternary (base 3) representation should only contain the digits 0 and 1. If any digit in the ternary representation is 2, it means that power of three is used more than once, which is not allowed. Thus, the solution involves converting the number to its base 3 representation and checking for the presence of the digit 2. Let's implement this solution in PHP: 1780. Check if Number is a Sum of Powers of Three <?php
/**
* @param Integer $n
* @return Boolean
*/
function checkPowersOfThree($n) {
while ($n > 0) {
$remainder = $n % 3;
if ($remainder == 2) {
return false;
}
$n = (int) ($n / 3);
}
return true;
}
// Test Cases
echo checkPowersOfThree(12) ? "true\n" : "false\n"; // Output: true
echo checkPowersOfThree(91) ? "true\n" : "false\n"; // Output: true
echo checkPowersOfThree(21) ? "true\n" : "false\n"; // Output: false
?> Explanation:
This approach efficiently checks the necessary condition by leveraging the properties of number representation in different bases, specifically base 3, ensuring that each power of three is used at most once. The time complexity is O(log n) due to the repeated division by 3, making it efficient even for large values of |
Beta Was this translation helpful? Give feedback.
We need to determine if a given integer
n
can be expressed as the sum of distinct powers of three. This means each power of three can be used at most once in the sum.Approach
The key insight here is to recognize that if a number can be represented as a sum of distinct powers of three, its ternary (base 3) representation should only contain the digits 0 and 1. If any digit in the ternary representation is 2, it means that power of three is used more than once, which is not allowed. Thus, the solution involves converting the number to its base 3 representation and checking for the presence of the digit 2.
Let's implement this solution in PHP: 1780. Check if Number is a Sum of Powers of Three