Skip to content

[258] Add Digits

https://leetcode.com/problems/add-digits/description/

  • algorithms
  • Easy (52.95%)
  • Source Code: 258.add-digits.py
  • Total Accepted: 233.5K
  • Total Submissions: 433.7K
  • Testcase Example: '38'

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?

python
class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        numstr = str(num)
        while len(numstr) > 1:
            nums = [int(item) for item in list(numstr)]
            numstr = str(sum(nums))

        return int(numstr)

Last updated: