-
Notifications
You must be signed in to change notification settings - Fork 4
/
Calculate Digit Sum of a String.py
48 lines (38 loc) · 1.07 KB
/
Calculate Digit Sum of a String.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution:
"""
Time: O(logk(n))
Memory: O(logk(n))
"""
def digitSum(self, s: str, k: int) -> str:
if len(s) <= k:
return s
return self.digitSum(self.round(s, k), k)
@classmethod
def round(cls, s: str, k: int) -> str:
return ''.join(map(cls.add_digits, cls.slice(s, k)))
@staticmethod
def add_digits(s: str) -> str:
return str(sum(int(d) for d in s))
@staticmethod
def slice(s: str, k: int):
for i in range(0, len(s), k):
yield s[i:i + k]
class Solution:
"""
Time: O(logk(n))
Memory: O(logk(n))
"""
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
s = self.round(s, k)
return s
@classmethod
def round(cls, s: str, k: int) -> str:
return ''.join(map(cls.add_digits, cls.slice(s, k)))
@staticmethod
def add_digits(s: str) -> str:
return str(sum(int(d) for d in s))
@staticmethod
def slice(s: str, k: int):
for i in range(0, len(s), k):
yield s[i:i + k]