2698. Find the Punishment Number of an Integer #1317
-
Topics: Given a positive integer The punishment number of
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the "punishment number" of a given integer Approach
Let's implement this solution in PHP: 2698. Find the Punishment Number of an Integer <?php
/**
* @param Integer $n
* @return Integer
*/
function punishmentNumber($n) {
$sum = 0;
for ($i = 1; $i <= $n; $i++) {
$square = $i * $i;
$s = strval($square);
if (canSplit($s, $i, 0, 0)) {
$sum += $square;
}
}
return $sum;
}
/**
* @param $s
* @param $target
* @param $index
* @param $currentSum
* @return bool
*/
function canSplit($s, $target, $index, $currentSum) {
$len = strlen($s);
if ($index == $len) {
return $currentSum == $target;
}
for ($splitLength = 1; $splitLength <= $len - $index; $splitLength++) {
$numStr = substr($s, $index, $splitLength);
$num = intval($numStr);
if ($currentSum + $num > $target) {
break;
}
if (canSplit($s, $target, $index + $splitLength, $currentSum + $num)) {
return true;
}
}
return false;
}
// Example Test Cases
echo punishmentNumber(10) . "\n"; // Output: 182
echo punishmentNumber(37) . "\n"; // Output: 1478
?> Explanation:
This approach efficiently checks all possible partitions using recursion with backtracking, ensuring that we only consider valid splits and sum calculations, leading to the correct result. |
Beta Was this translation helpful? Give feedback.
We need to determine the "punishment number" of a given integer
n
. The punishment number is defined as the sum of the squares of all integersi
(where1 <= i <= n
) such that the decimal representation ofi * i
can be partitioned into contiguous substrings whose sum equalsi
.Approach
i
from 1 ton
: For each integer, compute its square and convert the square into a string.i
, check if its square can be split into contiguous substrings such that the sum of these substrings equalsi
. This check is performed using a recursive helper function.