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...
2 Answers 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.
-
@Andrea Corbellini My mistake. Let me see if I can correct it.saulspatz– saulspatz2015年08月22日 16:02:11 +00:00Commented Aug 22, 2015 at 16:02
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 stringmap(int, '12348736')
: turns your string (list of characters) into a list of integers (appliesint
to every character)sum([1, 2, 3, 4, 8, 7, 3, 6])
: adds up all the digits in the list
-
2Omit the
list
:sum(map(int, str(total)))
.Dan D.– Dan D.2015年08月22日 15:56:45 +00:00Commented Aug 22, 2015 at 15:56
return self.addDigits(total)