Drill

ProblemsTypeScript › warmup

Sum of digits

easywarmupTypeScript

A checksum routine needs the digits of a number added together.

digitSum(amount: int) → int

Solve it in the editor →

Where you start

function digitSum(amount: number): number {
  
}

Worked examples

CallResult
digitSum(0)0
digitSum(7)7
digitSum(1234)10
digitSum(-204)6

Hint

Take the absolute value first, then peel digits off with % 10 and / 10.

Reference solution in TypeScript
function digitSum(amount: number): number {
  let x = Math.abs(amount);
  let total = 0;
  while (x > 0) {
    total += x % 10;
    x = Math.floor(x / 10);
  }
  return total;
}

The same problem in another language

More warmup problems in TypeScript