Easy: Warm-Ups · Problem 4 of 82

Digit Sum

EasyPython BasicsPython

Write digit_sum(n) that returns the sum of the digits of the integer n. The sign is ignored: digit_sum(-472) is 13.

Understand the problem

Work out how Python divides negative numbers. This is a common interview trap.

What is -7 // 2 in Python?

  1. -3
  2. -4

Floor division rounds down, towards minus infinity. -3.5 rounded down is -4. Many other languages round towards zero and give -3, so Python can surprise you.

What is -7 % 2 in Python? (The remainder takes the sign of the divisor.)

Python guarantees (a // b) * b + a % b == a. With a // b = -4: -4 * 2 + r = -7, so r = 1. The remainder is never negative when the divisor is positive.

A loop does digit = n % 10 and n //= 10 repeatedly, until n == 0. What goes wrong when n is negative?

  1. Nothing
  2. The digits are wrong and the loop never ends, because -1 // 10 is -1
  3. It raises an error

For n = -1, n // 10 is -1 again (rounded down), so n never reaches 0. The loop runs forever. The fix is to take the absolute value first.

Write the solution

Handle negatives and zero.

def digit_sum(n):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What is the simplest way to stop the sign from mattering?

Hint 2: the shape of the answer

Take abs(n). Then either turn it into text and add up int(ch) for each character, or use divmod(n, 10) in a loop.

Reflect

Solution: with text

def digit_sum(n):
    return sum(int(ch) for ch in str(abs(n)))

Another way: with arithmetic, no string

def digit_sum(n):
    n = abs(n)
    total = 0
    while n:
        n, digit = divmod(n, 10)
        total += digit
    return total

What this tests: abs, str, a generator expression, divmod, and knowing how // and % treat negatives.

Two ideas, both fine. Converting to a string is short and readable. The arithmetic version avoids the string and is what the interviewer means by "do it without converting to a string". divmod(n, 10) gives the quotient and the remainder in one step.

Cost: O(d) for a number with d digits.

What an interviewer might ask next: What if the interviewer asks for the digital root (keep adding digits until one digit is left)? Is there a formula? (For positive n it is 1 + (n - 1) % 9.)