Sum of Digits of String After Convert
Problem
Convert s to digits (a=1..z=26), concatenate, then replace by digit sum k times. Return the final number.
s = "iiii", k = 136def get_lucky(s, k):
digits = ''.join(str(ord(c) - 96) for c in s)
for _ in range(k):
digits = str(sum(int(d) for d in digits))
return int(digits)
function getLucky(s, k) {
let d = '';
for (const c of s) d += (c.charCodeAt(0) - 96);
for (let i = 0; i < k; i++) {
let sum = 0;
for (const c of d) sum += +c;
d = String(sum);
}
return Number(d);
}
class Solution {
public int getLucky(String s, int k) {
StringBuilder d = new StringBuilder();
for (char c : s.toCharArray()) d.append(c - 'a' + 1);
String cur = d.toString();
for (int i = 0; i < k; i++) {
int sum = 0;
for (char c : cur.toCharArray()) sum += c - '0';
cur = String.valueOf(sum);
}
return Integer.parseInt(cur);
}
}
int getLucky(string s, int k) {
string d;
for (char c : s) d += to_string(c - 'a' + 1);
for (int i = 0; i < k; i++) {
int sum = 0;
for (char c : d) sum += c - '0';
d = to_string(sum);
}
return stoi(d);
}
Explanation
The task is a literal two-stage recipe: first turn the letters into a long string of digits, then repeatedly collapse that string into its digit sum a total of k times.
For the conversion, each letter maps to its alphabet position: a=1, b=2, ... z=26. In code that is ord(c) - 96. We glue those numbers together into one big string. So "iiii" becomes "9999" because i is the 9th letter.
Then we loop k times. Each pass replaces the current string with the sum of its individual digits, written back as a string: digits = str(sum(int(d) for d in digits)).
Example: with s = "iiii" and k = 1, we get "9999", then one round of summing gives 9+9+9+9 = 36, so the answer is 36.
It works because each round shrinks a big number into a much smaller one, and after exactly k rounds we convert the final string back to an integer with int(digits).