[LeetCode] Sum of Digits of String After Convert

1945. Sum of Digits of String After Convert

You are given a string s consisting of lowercase English letters, and an integer k.

First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, …, 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total.

For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:

  • Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124
  • Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
  • Transform #2: 17 ➝ 1 + 7 ➝ 8

Return the resulting integer after performing the operations described above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int getLucky(string s, int k) {
k--;
int res = 0;
for(auto& ch : s) {
int x = ch - 'a' + 1;
while(x) {
res += x % 10;
x /= 10;
}
}
while(k--) {
int nres = 0;
while(res) {
nres += res % 10;
res /= 10;
}
res = nres;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/03/PS/LeetCode/sum-of-digits-of-string-after-convert/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.