Skip to content

Commit 0d6b3bc

Browse files
my solution for 1945
1 parent a238aeb commit 0d6b3bc

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

problems/1945/jeremymanning.md

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,41 @@
11
# [Problem 1945: Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert/description/?envType=daily-question)
22

33
## 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)`
414

515
## 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+
619

720
## Attempted solution(s)
821
```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)
1132
```
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+
![Screenshot 2024-09-02 at 8 41 31 PM](https://github.com/user-attachments/assets/0a1d3f63-c163-4bfb-a8ec-286ee3b9c0cc)
40+
41+
Solved!

0 commit comments

Comments
 (0)