Teaching Kids Programming: Videos on Data Structures and Algorithms
Given a positive integer num, return the sum of its digits. Bonus: Can you do it without using strings?
Constraints
0 ≤ num < 2 ** 31Example 1
Input
num = 123
Output
6
Explanation
Since 6 = 1 + 2 + 3Example 2
Input
num = 50
Output
5
Explanation
Since 5 = 5 + 0
Sum of the Digits by Converting to String
By converting the number to string, we can actually iterate the digits easily:
1 2 3 4 5 6 | def sumOfDigits(n): s = str(n) ans = 0 for i in s: ans += i return ans |
def sumOfDigits(n): s = str(n) ans = 0 for i in s: ans += i return ans
A more fancy Python code using list comprehension via sum method:
1 2 | def sumOfDigits(n): return sum([int(x) for x in str(n)]) |
def sumOfDigits(n): return sum([int(x) for x in str(n)])
Recursive Summing up the Digits
We know the sum of the least significant digit (rightmost), and we can add it together with the others – which can be recursively solved. The terminal case is that when given number is zero, the sum is zero.
1 2 3 4 | def sumOfDigits(n): if n == 0: return 0 return n % 10 + sumOfDigits(n // 10) |
def sumOfDigits(n): if n == 0: return 0 return n % 10 + sumOfDigits(n // 10)
Suming up digits by Extracting Digits one by one
Similar to the above recursive approach, but implemented using a loop iterativedly.
1 2 3 4 5 6 | def sumOfDigits(n): ans = 0 while n > 0: ans += n % 10 n //= 10 return ans |
def sumOfDigits(n): ans = 0 while n > 0: ans += n % 10 n //= 10 return ans
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Teaching Kids Programming - Two Algorithms to Compute Inverse Factorials
Next Post: Unique Occurrences Algorithms for Numbers