326. Power of Three #2047
-
Topics: Given an integer An integer Example 1:
Example 2:
Example 3:
Constraints:
Follow up: Could you solve it without loops/recursion? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if a given integer ApproachThe approach leverages mathematical properties of powers of three within the constraints of 32-bit signed integers. The key insight is that the largest power of three that fits within a 32-bit signed integer is 319 = 1162261467. For any positive integer
This approach efficiently checks the power of three condition without using loops or recursion, leveraging mathematical properties for optimal performance. Let's implement this solution in PHP: 326. Power of Three <?php
/**
* @param Integer $n
* @return Boolean
*/
function isPowerOfThree($n) {
if ($n <= 0) {
return false;
}
$max_power_three = 1162261467;
return ($max_power_three % $n == 0);
}
// Test cases
var_dump(isPowerOfThree(27)); // true
var_dump(isPowerOfThree(0)); // false
var_dump(isPowerOfThree(-1)); // false
var_dump(isPowerOfThree(9)); // true
var_dump(isPowerOfThree(45)); // false
?> Explanation:
This method efficiently leverages mathematical properties to avoid loops or recursion, providing an optimal solution with constant time complexity O(1). |
Beta Was this translation helpful? Give feedback.
We need to determine if a given integer
n
is a power of three. An integern
is a power of three if there exists an integerx
such thatn == 3x
.Approach
The approach leverages mathematical properties of powers of three within the constraints of 32-bit signed integers. The key insight is that the largest power of three that fits within a 32-bit signed integer is 319 = 1162261467. For any positive integer
n
to be a power of three, it must be a divisor of 319. This is because the divisors of 319 are exclusively 3k for k = 0 to 19, which covers all possible powers of three within the 32-bit signed integer range.n
is less than or equal to zero, it cannot be …