Skip to content
thesarfo

Reference

Counting Digits

Counting the number of individual digits in a number by repeatedly dividing by 10.

views 0

Given an input number, say 554, return the total number of individual digits in it.

Initialize a counter variable and set it to 0. We update this counter each time we extract a digit from the input number, by repeatedly dividing the number by 10. Let’s take it this way, if your input number is 770:

  • Increment the counter by 1 because 770 is not zero.
  • Divide 770 by 10, which gives us 77.
  • Increment the counter again because 77 is not zero.
  • Divide 77 by 10, which gives us 7.
  • Increment the counter once more because 7 is not zero.
  • Divide 7 by 10, which gives us 0.

On each iteration where we divide our input number by 10, we update the result to the input number itself (n = n / 10). We continue this process until the result of dividing the input number by 10 is 0. By that point, our counter reflects the total number of individual digits.

static int evenlyDivides(int N){
int counter = 0;
while (N > 0){
counter +=1;
N = N / 10;
}
return counter;
}