Get the length of a number by only using modulus [closed]

uint num=/* your input */;

// that's the number of digits required to print
// num in base 10; 
uint ceil_log10 = 1;
for(uint i = 10; num > 10; i = i*10) {
  num -= (num % i);
  ceil_log10++;
}

Any number < 10 needs one digit.

Any number >= 10 will enter the cycle, which eliminates the digits from least to the most significant digit (using modulus) until nothing remains.

If you are not allowed to use multiplication, you can substitute it by repeated additions:

uint num=/* your input */;

// that's the number of digits required to print
// num in base 10; 
uint ceil_log10 = 1;
for(uint i = 10; num > 10; /* no multiplication 4 you!! i = i*10 */) {
  num -= (num % i);
  ceil_log10++;

  uint nextPower10=i;
  for(int j=0; j<9; j++) {
    nextPower10+=i;
  }
  i=nextPower10;
}

Browse More Popular Posts

Leave a Comment