869. Reordered Power of 2 #2035
-
Topics: You are given an integer Return Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if we can reorder the digits of a given integer Approach
Let's implement this solution in PHP: 869. Reordered Power of 2 <?php
/**
* @param Integer $n
* @return Boolean
*/
function reorderedPowerOf2($n) {
$s = (string)$n;
$len = strlen($s);
$freq_n = count_frequency($s);
$p = "1";
while (strlen($p) <= $len) {
$current_len = strlen($p);
if ($current_len == $len) {
$freq_p = count_frequency($p);
if ($freq_p == $freq_n) {
return true;
}
}
$p = multiply_by_2($p);
}
return false;
}
/**
* @param $s
* @return array
*/
function count_frequency($s) {
$freq = array_fill(0, 10, 0);
$length = strlen($s);
for ($i = 0; $i < $length; $i++) {
$digit = (int)$s[$i];
$freq[$digit]++;
}
return $freq;
}
/**
* @param $s
* @return string
*/
function multiply_by_2($s) {
$result = '';
$carry = 0;
$length = strlen($s);
for ($i = $length - 1; $i >= 0; $i--) {
$digit = (int)$s[$i];
$product = $digit * 2 + $carry;
$carry = (int)($product / 10);
$digit_result = $product % 10;
$result = (string)$digit_result . $result;
}
if ($carry) {
$result = (string)$carry . $result;
}
return $result;
}
// Test cases
var_dump(reorderedPowerOf2(1)); // true
var_dump(reorderedPowerOf2(10)); // false
?> Explanation:
This approach efficiently checks all possible powers of two with the same digit length as |
Beta Was this translation helpful? Give feedback.
We need to determine if we can reorder the digits of a given integer
n
such that the resulting number (with no leading zeros) is a power of two. The solution involves checking all possible powers of two that have the same number of digits asn
and comparing their digit frequencies with that ofn
. If any power of two matches the digit frequency ofn
, then it's possible to reordern
to form that power of two.Approach
n
to compare with potential powers of two.