2081. Sum of k-Mirror Numbers #1842
-
Topics: A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k.
Given the base Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the sum of the Approach
Let's implement this solution in PHP: 2081. Sum of k-Mirror Numbers <?php
/**
* @param Integer $k
* @param Integer $n
* @return Integer
*/
function kMirror($k, $n) {
$res = array();
$L = 1;
while (count($res) < $n) {
if ($L % 2 == 0) {
$d = $L / 2;
$start = (int)pow(10, $d-1);
$end = (int)(pow(10, $d) - 1);
for ($x = $start; $x <= $end; $x++) {
$s = (string)$x;
$num_str = $s . strrev($s);
$num_val = (int)$num_str;
if (is_basek_palindrome($num_val, $k)) {
$res[] = $num_val;
if (count($res) == $n) {
break 2;
}
}
}
} else {
$d = (int)(($L+1)/2);
$start = (int)pow(10, $d-1);
$end = (int)(pow(10, $d) - 1);
for ($x = $start; $x <= $end; $x++) {
$s = (string)$x;
$rev = strrev($s);
$num_str = $s . substr($rev, 1);
$num_val = (int)$num_str;
if (is_basek_palindrome($num_val, $k)) {
$res[] = $num_val;
if (count($res) == $n) {
break 2;
}
}
}
}
$L++;
}
return array_sum($res);
}
/**
* @param $num
* @param $k
* @return bool
*/
function is_basek_palindrome($num, $k) {
if ($num == 0) {
return true;
}
$s = '';
$n = $num;
while ($n > 0) {
$r = $n % $k;
$s = (string)$r . $s;
$n = (int)($n / $k);
}
return $s === strrev($s);
}
// Test cases
echo kMirror(2, 5) . PHP_EOL; // 25
echo kMirror(3, 7) . PHP_EOL; // 499
echo kMirror(7, 17) . PHP_EOL; // 20379000
?> Explanation:
This approach efficiently generates palindromic numbers in increasing order and checks their validity in base-k, ensuring optimal performance for the given constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the sum of the
n
smallest k-mirror numbers. A k-mirror number is a positive integer that reads the same both forward and backward in both base-10 and base-k. The solution involves generating palindromic numbers in base-10 and checking if they are also palindromic in base-k.Approach
Generate Palindromic Numbers in Base-10:
L
:x
with its reverse. For example, ifx
is 12, the palindrome is 1221.x
with the reverse ofx
without …