If I want to find the sum of the digits of a number, i.e. :
- Input:
932
- Output:
14
, which is(9 + 3 + 2)
What is the fastest way of doing this?
I instinctively did:
sum(int(digit) for digit in str(number))
and I found this online:
sum(map(int, str(number)))
Which is best to use for speed, and are there any other methods which are even faster?
You can also use this:
print(sum) // make sure to add space above this line
You can try this
If you want to keep summing the digits until you get a single-digit number (one of my favorite characteristics of numbers divisible by 9) you can do:
Which actually turns out to be pretty fast itself...
you can also try this with built_in_function called divmod() ;
you can take any number of digit