Sum All Digits of a Number | Skilled.dev
Interview Question

Sum Digits

Given a positive integer as an input, write a function sumDigits that calculates the sum of all the digits of this number.

There is one constraint: you cannot convert the input number to another data type.

sumDigits(11) // 1 + 1 = 2
sumDigits(123) // 1 + 2 + 3 = 6
sumDigits(5510) // 5 + 5 + 1 + 0 = 11

Breakdown

Loading...

Table of Contents

Validate My Answer

  1. If we could convert the input integer to a string or another data structure that was iteratable, it would be easy to walk through each digit and add them together. Now you need to be a little more creative.

  2. The input is an integer which has a fixed upper limit. For example, the largest unsigned 64-bit integer is 2^64 - 1 = 18,446,744,073,709,551,615. This is 20 total digits, so your Big O will actually be constant time O(1) because it can't grow arbitrarily large.

  3. You can solve this iteratively or recursively. In either case, you will likely need to modulo % and divide by 10.

Loading...

Table of Contents

Test Results

Run your code and see results here...

const sumDigits = (number) => {
  // Your solution here
}
// Upgrade for full course access
// Upgrade for full course access

Sum Digits

Given a positive integer as an input, write a function sumDigits that calculates the sum of all the digits of this number.

There is one constraint: you cannot convert the input number to another data type.

sumDigits(11) // 1 + 1 = 2
sumDigits(123) // 1 + 2 + 3 = 6
sumDigits(5510) // 5 + 5 + 1 + 0 = 11
const sumDigits = (number) => {
  // Your solution here
}
// Upgrade for full course access
// Upgrade for full course access