Search code examples
cdecimaldigits

This program doesn't work properly for decimals more than 10 digits?


The below code is used to count number of digit in a given decimal. The problem is that it doesn't count digits more than 10.

int NumDigits(int n) {
  int digits = 0;
  if (n <= 0) {
    n = -n;
    ++digits;
  }

  while (n) {
    n /= 10;
    ++digits;
  }

  return digits;
}

Solution

  • It seems like your toolchain has a 32-bit int type. The maximum value representable in such a type is 231-1, or 2,147,483,647. As you can see, that's a 10-digit number. You'll need to use a different type that supports larger numbers if you want to use this kind of an algorithm.