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...

Anand S Kumar
91.3k18 gold badges196 silver badges179 bronze badges
asked Aug 22, 2015 at 14:36
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.

answered Aug 22, 2015 at 15:53
1
  • @Andrea Corbellini My mistake. Let me see if I can correct it. Commented Aug 22, 2015 at 16:02
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
answered Aug 22, 2015 at 14:48
1
  • 2
    Omit the list: sum(map(int, str(total))). Commented Aug 22, 2015 at 15:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.