Sum of Digits in a Given Number

Pattern: Recursion basics

easy

Add up a number's digits recursively, as its last digit plus the digit sum of the number without that digit.

The problem

You are given a whole number n that is zero or more and fits in a 32-bit integer. Return the sum of its decimal digits, using recursion. For example, the digit sum of 4729 is 4 + 7 + 2 + 9 = 22.

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name sumOfDigits and the limits above are this guide's own.

Think first

  • Which numbers have a digit sum you know without any work?
  • How do you get a smaller number out of 4729, and how is its digit sum related to the one you want?
  • How deep can the recursion go for the largest 32-bit number?

Hints

    Brute force, and why it fails

    The loop version peels digits with % 10 and / 10 and adds them to a running total, using constant memory. Turning the number into text and adding the characters also works. All of these are fine, because there are at most 10 digits. Here the recursive form is the exercise, and with at most 10 levels it is perfectly safe.

    The key insight

    Split the number into "last digit" and "everything before it". The second part is a smaller number with the same question, so the recursion is n % 10 + sumOfDigits(n / 10), stopping at a single digit.

    Dry run

    s(4729)0 
    waiting9 + ?

    Call sumOfDigits(4729). It is 10 or more, so it needs 9 + sumOfDigits(472) and waits. The array is the call stack.

    Step 1 of 7

    The plan

    function sumOfDigits(n):
        if n < 10:
            return n                              # a single digit
        return n mod 10 + sumOfDigits(n div 10)   # last digit plus the rest
    

    Complexity

    Time
    O(d)
    Space
    O(d)

    d is the number of digits, at most 10. There is one call per digit, and they are all open at the deepest point.

    Edge cases

    • n = 0 returns 0, and a single digit returns itself.
    • 10 returns 1: the 0 adds nothing.
    • 2147483647 has a digit sum of 46, and the recursion is only 10 levels deep.
    • 1000000000 returns 1.
    I've built my logic, show the code

    Java

    class Solution {
        public int sumOfDigits(int n) {
            if (n < 10) {
                return n;                               // base case: a single digit
            }
            return n % 10 + sumOfDigits(n / 10);        // last digit plus the digits before it
        }
    }

    C++

    class Solution {
    public:
        int sumOfDigits(int n) {
            if (n < 10) {
                return n;                               // base case: a single digit
            }
            return n % 10 + sumOfDigits(n / 10);        // last digit plus the digits before it
        }
    };

    Python

    class Solution:
        def sumOfDigits(self, n):
            if n < 10:
                return n                                    # base case: a single digit
            return n % 10 + self.sumOfDigits(n // 10)       # last digit plus the digits before it

    Common mistakes

    • Leaving out the base case. The step keeps calling with 0 / 10, which is still 0, so the calls never end.
    • Using / in Python 3, which gives a decimal. Use //.
    • Adding n instead of n % 10 in the step.

    Similar problems