A huge share of number problems reduce to one loop that peels digits off a number, right to left. Two operations do all the work, both from earlier modules:
n % 10gives the last digit.n / 10(integer division) drops the last digit.
Repeat until n becomes 0 and you have visited every digit:
def solve(n):
count = 0
while n > 0:
digit = n % 10 # grab last digit
count += 1 # ... do something with it
n = n // 10 # drop last digit
return count # here: how many digits n has
long long solve(long long n) {
long long count = 0;
while (n > 0) { count++; n /= 10; }
return count;
}
This digit-peeling loop is the running-total pattern applied to digits: keep an
accumulator, update it with each digit, shrink n each pass. Counting digits, summing digits,
finding the largest digit — all are the same loop with a different update. For inputs that
might be 0 or negative, handle those as small special cases (0 has one digit; take the absolute
value first if negatives are allowed).