d891320478's blog

By d891320478, 12 years ago, In English

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

It may cause error because of accuracy.

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
12 years ago, # |
  Vote: I like it +3 Vote: I do not like it

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.

  • »
    »
    12 years ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    Here's an even faster way :)

    1. Integer.valueOf(x).toString().length();

    2. (""+x).toString().length();

    • »
      »
      »
      12 years ago, # ^ |
        Vote: I like it +1 Vote: I do not like it

      even faster and in C:

      len=sprintf(buf,"%d",x);

      • »
        »
        »
        »
        12 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Quite elegant, but, the code i posted works in every base and takes a lot less time because it doesn't rely on string operations. Whatever suits people's needs.

      • »
        »
        »
        »
        12 years ago, # ^ |
        Rev. 2   Vote: I like it 0 Vote: I do not like it

        Yours is shorter, but it takes longer to type.

        1. Integer.toString(x).length();

        2. Integer.toString(x,17).length(); // Different base

        Since it's a string operation I use it when I know it won't effect too much on the speed.