0

I'm trying to write a function to add the digits of a given number repeatedly until I have a single digit.

So addDigits(345) = 12, 1+2 = 3, so this should return 3

Here's my attempt:

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        if (num >= 0 and num < 10):
            return num
        else:
            total = 0
            while (num >= 10):
                total += (num % 10)
                num /= 10
            total += num
            self.addDigits(total)

On input 10, I'm getting null back and I have no idea why. I've traced through the code and it looks right to me...

1
  • 4
    You need to return the result of recursive call. return self.addDigits(total) Commented Aug 22, 2015 at 14:37

2 Answers 2

2

The old technique of "casting out nines" gives a quick answer

def sumOfDigits(x):
    if x == 0: return 0 
    y = x % 9
    return 9 if y == 0 else y

An example shows why this works:

433 = 4*(99+1) +3*(9+1) +2 = 4*99 + 3*9 + (4+3+3)

reducing modulo 9 gives (4+3+3) (mod 9)

As Andrea's comment below points out, this gives the wrong answer when the sum of the digits is congruent to 9.

Sign up to request clarification or add additional context in comments.

1 Comment

@Andrea Corbellini My mistake. Let me see if I can correct it.
1

Here is one approach that splits your number into individual digits, and continuously sums them until you end up with a single digit.

total = 12348736

while len(str(total)) > 1:
    total = sum(map(int,str(total)))

print total

EDIT: Just to explain this further:

  • str(12348736): turns your number into a string
  • map(int, '12348736'): turns your string (list of characters) into a list of integers (applies int to every character)
  • sum([1, 2, 3, 4, 8, 7, 3, 6]): adds up all the digits in the list

1 Comment

Omit the list: sum(map(int, str(total))).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.