TypeScript bootcamp · Lab 10

Sum of digits

easyWhile10 minLesson: While

Read the question, write TypeScript on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read a non-negative integer and print the sum of its digits.

Input. One integer ≥ 0.

Output. Digit sum.

Examples

Example 1
Input
123
Output
6
Example 2
Input
1001
Output
2
Hint
  1. While n > 0: add n % 10, then n = Math.floor(n / 10).
Show correct code

Peek only after you have tried. You can still Check your own version.

let n: number = Number(readLine());
let s = 0;
while (n > 0) { s += n % 10; n = Math.floor(n / 10); }
console.log(s);
main.tstsc · readLine() · Ctrl + Enter
ResultIdle
Run to see output. Check grades the tests.