Skip to content
ExamSpine

Lesson 4.6 · Write it

Sum of digits

A functionPython or Java7 tests, 4 of them hidden

On a phone? Put the lines in order instead

Write a function that returns the sum of the digits of a whole number.

  1. n is a whole number from 0 to 999999999.
  2. The sum of the digits of 0 is 0.

Write helper functions for "last digit" (the remainder when dividing by 10) and "remove last digit" (whole-number division by 10), and use them. Do not convert the number to text.

Only the number your function returns is checked.

def sum_of_digits(n: int) -> int

You cannot use these in this question:

  • str()
  • len()
  • repr()
  • format()
  • list()
  • import math

This question is about using arithmetic to extract digits, so converting to text is not allowed.

Examples

Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.

  • sum_of_digits(123) should return 6: 1 + 2 + 3 = 6 (rule 1)
  • sum_of_digits(0) should return 0: zero has a digit sum of 0 (rule 2)
  • sum_of_digits(9) should return 9: a single digit (rule 1)

public static int sumOfDigits(int n)

Checking whether Java answers can run here.

You cannot use these in this question:

  • String.valueOf()
  • Integer.toString()
  • .length()
  • .toCharArray()
  • .charAt()
  • .chars()

This question is about using arithmetic to extract digits, so converting to text is not allowed.

Examples

Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.

  • sumOfDigits(123) should return 6: 1 + 2 + 3 = 6 (rule 1)
  • sumOfDigits(0) should return 0: zero has a digit sum of 0 (rule 2)
  • sumOfDigits(9) should return 9: a single digit (rule 1)
solution.pySolution.java