Sum of Digits of a Number

Easy ⏱ 8 min 83% acceptance ★★★★★ 4.9
Write a function digit_sum(n) that returns the sum of the digits of a non-negative integer n, using a while loop and integer arithmetic (% 10 and // 10) — not string conversion.

Examples

Example 1
Input
digit_sum(1234)
Output
10
Explanation

1+2+3+4 = 10.

Example 2
Input
digit_sum(7)
Output
7
Explanation

Single digit sums to itself.

Example 3
Input
digit_sum(0)
Output
0
Explanation

Zero has digit sum zero.

Constraints

  • n is a non-negative integer.
  • Must not convert n to a string.

Topics

Loopswhile loop

Companies

InfosysCapgemini

Hints

Hint 1

`n % 10` gives the last digit; `n // 10` drops it.

Hint 2

Loop while n is greater than 0 (handle the n == 0 case separately or as a special starting check).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.