Last active
March 22, 2016 02:07
-
-
Save ideadsnow/6f74d808a21e9a16e6ae to your computer and use it in GitHub Desktop.
[LeetCode] 258. Add Digits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
def addDigits_recursion(self, num): | |
""" | |
:type num: int | |
:rtype: int | |
""" | |
num_str = str(num) | |
if len(num_str) == 1: | |
return num | |
new_num = 0 | |
for s in num_str: | |
new_num += int(s) | |
return self.addDigits_recursion(new_num) | |
def addDigits_loop(self, num): | |
""" | |
:type num: int | |
:rtype: int | |
""" | |
num_str = str(num) | |
while len(num_str) != 1: | |
new_num = 0 | |
for s in num_str: | |
new_num += int(s) | |
num_str = str(new_num) | |
return int(num_str) | |
# 自行 Google -> 数根 Digits Root | |
def addDigits_formula(num): | |
if num / 9 == 0: | |
return num | |
if num % 9 == 0: | |
return 9 | |
return num % 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment