Digit Sum
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?
-3-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?
- Nothing
- The digits are wrong and the loop never ends, because
-1 // 10is-1 - 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.)
VISIBLE = 3
CASES = [
((472,), 13, 'a positive number'),
((-472,), 13, 'a negative number'),
((0,), 0, 'zero'),
((9,), 9, 'one digit'),
((1000,), 1, 'zeros inside'),
((999999999,), 81, 'all nines'),
((-5,), 5, 'a negative single digit'),
((10 ** 18,), 1, 'a very large number'),
]