Interview Question
Share Lesson

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.

 

Breakdown

Loading...
Follow teacher
Share:

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...
Follow teacher
Share:

Table of Contents

Test Results

Run your code and see results here...

/**
 * @param {int} number
 * @return {int}
 */
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.

 
/**
 * @param {int} number
 * @return {int}
 */
const sumDigits = (number) => {
  // Your solution here
}
// Upgrade for full course access
// Upgrade for full course access