1945. Sum of Digits of String After Convert #469
-
Topics: You are given a string First, convert For example, if
Return the resulting integer after performing the operations described above. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can break down the solution into two main steps:
Let's implement this solution in PHP: 1945. Sum of Digits of String After Convert <?php
function getLucky($s, $k) {
// Step 1: Convert the string into an integer
$numStr = '';
for ($i = 0; $i < strlen($s); $i++) {
$numStr .= (ord($s[$i]) - ord('a') + 1);
}
// Step 2: Transform the integer by summing its digits k times
for ($i = 0; $i < $k; $i++) {
$sum = 0;
for ($j = 0; $j < strlen($numStr); $j++) {
$sum += intval($numStr[$j]);
}
$numStr = strval($sum);
}
return intval($numStr);
}
// Test cases
echo getLucky("iiii", 1) . "\n"; // Output: 36
echo getLucky("leetcode", 2) . "\n"; // Output: 6
echo getLucky("zbax", 2) . "\n"; // Output: 8
?> Explanation:
Test Cases:
This solution is efficient given the constraints and will work well within the provided limits. |
Beta Was this translation helpful? Give feedback.
We can break down the solution into two main steps:
Convert the string
s
into an integer:Transform the integer by summing its digits
k
times:k
times.Let's implement this solution in PHP: 1945. Sum of Digits of String After Convert