Add the digits
Inputs
n is a whole number from 0 to 1,000,000.
Your tasks
- Create a number
totalthat starts at 0 and a copyrestofn. - Use a
whileloop that runs whilerestis more than 0. Each round, add the last digit ofrest(the remainder when dividing by 10) tototal, then drop that digit. - Complete
digitSumso it returnstotal. Return it, do not print it.
Example
With n = 4821, digitSum returns 15.
Rules
- Do not turn the number into text.
Test data
TEST DATA 1: n is 4821
TEST DATA 2: n is 0
Practice focus
While loops and early exits, for when you don't know how many rounds you need. Binary search, the Euclidean algorithm and graph search are all while loops with a clear stopping rule.