Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example:


Input: 38
Output: 2 
Explanation: 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?

Source: leetcode | Difficulty: EASY
Tags: Number theory

Mathematics

Starter code: class Solution:
    def addDigits(self, num: int) -> int:
        

Solutions:
class Solution:

	def addDigits(self, num):
		if num == 0:
			return 0
		return 1 + (num - 1) % 9


class Solution:

	def addDigits(self, num):
		result = 0
		while num >= 10:
			(num, rem) = divmod(num, 10)
			num += rem
		return num


class Solution:

	def addDigits(self, num):
		if num < 10:
			return num
		else:
			return self.addDigits(num % 10 + self.addDigits(num // 10))


class Solution:

	def addDigits(self, num):
		if num < 10:
			return num
		curr_num = num
		total = 0
		while True:
			while curr_num > 0:
				digit = curr_num % 10
				total += digit
				curr_num = curr_num // 10
			if total < 10:
				return total
			else:
				curr_num = total
				total = 0


class Solution:

	def addDigits(self, num):
		while num // 10 > 0:
			rlt = 0
			while num > 0:
				rlt += num % 10
				num //= 10
			num = rlt
		return num


class Solution:

	def addDigits(self, num):
		while len(str(num)) > 1:
			newNum = 0
			while num > 0:
				newNum += num % 10
				num = num // 10
			num = newNum
		return num


class Solution:

	def addDigits(self, num):
		if num < 10:
			return num
		else:
			return self.addDigits(sum([int(x) for x in str(num)]))


class Solution:

	def addDigits(self, num):
		while True:
			if num < 10:
				return num
			else:
				num = sum([int(i) for i in str(num)])


class Solution:

	def addDigits(self, num):
		return 9 if num != 0 and num % 9 == 0 else num % 9


class Solution:

	def addDigits(self, num):
		return num if num < 10 else num % 9 if num % 9 != 0 else 9


class Solution:

	def addDigits(self, num):
		if num == 0:
			return 0
		mod = num % 9
		return mod if mod != 0 else 9