Skip to content

Instantly share code, notes, and snippets.

@tamlt2704
Created December 31, 2017 11:43
Show Gist options
  • Select an option

  • Save tamlt2704/0593461715b5de5881bc5a2d91e728a0 to your computer and use it in GitHub Desktop.

Select an option

Save tamlt2704/0593461715b5de5881bc5a2d91e728a0 to your computer and use it in GitHub Desktop.
#Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
#For example:
#Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
#Follow up:
#Could you do it without any loop/recursion in O(1) runtime?
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
def imod(x, y):
s = 1
if x < 0:
s = -1
return s * ((x*s) % y)
return 1 + imod(num-1, 9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment