-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAddDigits.py
More file actions
44 lines (39 loc) · 947 Bytes
/
AddDigits.py
File metadata and controls
44 lines (39 loc) · 947 Bytes
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
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/add-digits/
"""
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
if num < 10:
return num
return 1 + (num - 1) % 9
def addDigits_recursive(self, num):
"""
:type num: int
:rtype: int
"""
if num < 10:
return num
return self.addDigits(sum(map(int, str(num))))
def addDigits_loop(self, num):
"""
:type num: int
:rtype: int
"""
if num < 10:
return num
while True:
pre, digit = divmod(num, 10)
total = digit
while pre > 10:
pre, digit = divmod(pre, 10)
total += digit
total += pre
if total < 10:
return total
else:
num = total