Блог пользователя d891320478

Автор d891320478, 14 лет назад, По-английски

Don't use (int)log10(n)+1 to count the length of n.

It may cause error because of accuracy.

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
14 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

Instead, try this:

int digits(int x){ //works for x>0, for x<0 simply put x=-x, and for x==0 return 1
   int result=0;
   while (x>0){
      result++;
      x/=10;
   }
   return result;
}

It's just a few lines of code. I know speed is crucial here, but this can be typed in 15 seconds. Using floating point arithmetic for things that can be done with integer arithmetic is not recommended.