Take a number apart digit by digit with a loop, remainders and whole-number division.
What to build
A program that adds up the digits of a number and counts them.
Requirements
- Read a number n.
- Print
Digit sum: SandDigits: D. The number 0 has one digit.
Input
One integer n.
Output
Two lines.
Constraints
0 ≤ n ≤ 1000000000.
Example
Input:
12345
Output:
Digit sum: 15
Digits: 5
Why it works
Each round of the loop takes the last digit with % 10 and drops it with intdiv, until nothing is left.
Examples
Example 1 · Input
12345
Expected output
Digit sum: 15 Digits: 5
Example 2 · Input
7
Expected output
Digit sum: 7 Digits: 1
Hints
Hint 1
The last digit of n is n % 10, and intdiv(n, 10) removes it.
Hint 2
Use do-while so that the number 0 counts as one digit.
Solution
Show one correct solution (try it yourself first)
<?php
$n = (int) trim(fgets(STDIN));
$sum = 0;
$digits = 0;
do {
$sum += $n % 10;
$n = intdiv($n, 10);
$digits++;
} while ($n > 0);
echo "Digit sum: $sum\n";
echo "Digits: $digits\n";