Sometimes you need to calculate the sum of digits of an integer.
A straightforward approach is:
int sumDigits(int num) {
int result = 0;
while (num > 0) {
result += num % 10;
num /= 10;
}
return result;
}
This implementation performs both a modulo (%) and an integer division (/) on every iteration.
Reformulating the Problem
For simplicity, assume:
0 <= num <= 9999
Represent the number as: