|
1 | 1 | # [Problem 1945: Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/description/?envType=daily-question)
|
2 | 2 |
|
3 | 3 | ## Initial thoughts (stream-of-consciousness)
|
| 4 | +- Another easy one 🥳! |
| 5 | +- Let's hard code in the lowercase letters (`letters = 'abcdefghijklmnopqrstuvwxyz'`) |
| 6 | +- Then we can make a `letter2num` decoder: `letter2num = {c: str(i + 1) for i, c in enumerate(letters)}` |
| 7 | +- Next, we just replace each letter with it's number, stitch it into a string, and convert to an integer: `num = int("".join([letter2num[c] for c in s]))` |
| 8 | +- Finally, loop through `k` times to sum the digits: |
| 9 | +```python |
| 10 | +for _ in range(k): |
| 11 | + num = str(sum([int(i) for i in str(num)])) |
| 12 | +``` |
| 13 | +- And then we just return `int(num)` |
4 | 14 |
|
5 | 15 | ## Refining the problem, round 2 thoughts
|
| 16 | +- There are no tricky edge cases, as far as I can tell; `k` is always at least 1, and the strings aren't super long so we don't need to worry about overflow issues |
| 17 | +- Let's try it! |
| 18 | + |
6 | 19 |
|
7 | 20 | ## Attempted solution(s)
|
8 | 21 | ```python
|
9 |
| -class Solution: # paste your code here! |
10 |
| - ... |
| 22 | +class Solution: |
| 23 | + def getLucky(self, s: str, k: int) -> int: |
| 24 | + letters = 'abcdefghijklmnopqrstuvwxyz' |
| 25 | + letter2num = {c: str(i + 1) for i, c in enumerate(letters)} |
| 26 | + |
| 27 | + num = int("".join([letter2num[c] for c in s])) |
| 28 | + for _ in range(k): |
| 29 | + num = str(sum([int(i) for i in str(num)])) |
| 30 | + |
| 31 | + return int(num) |
11 | 32 | ```
|
| 33 | +- Given test cases pass |
| 34 | +- Let's try some other random ones: |
| 35 | + - `s = "asdlkoifhawioefuh", k = 5`: pass |
| 36 | + - `s = "dkfjkjdfijshdeweskjhaskljdfhjsldkjf", k = 4`: pass |
| 37 | +- I think we're good; submitting... |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | +Solved! |
0 commit comments