Coding problem · Easy · Basics

Sum of Digits

Easy Algorithms & data structures

Return the sum of the digits of the non-negative integer n.

Example 1

Input: n = 1234
Output: 10

Example 2

Input: n = 0
Output: 0

Hints

Hint 1

n % 10 is the last digit; integer division by 10 removes it.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(digits) · Space O(1)

Repeatedly add n % 10 and divide n by 10 (integer division) until it reaches 0. Converting to a string and adding characters also works.

Reference solution

function sumOfDigits(n) {
  let total = 0;
  while (n > 0) { total += n % 10; n = Math.floor(n / 10); }
  return total;
}

Was this page helpful?