Finding the number of digits of an integer

前端 未结 17 2188
难免孤独
难免孤独 2020-12-07 16:32

What is the best method to find the number of digits of a positive integer?

I have found this 3 basic methods:

  • conversion to string

             
    
    
            
17条回答
  •  青春惊慌失措
    2020-12-07 17:10

    This algorithm might be good also, assuming that:

    • Number is integer and binary encoded (<< operation is cheap)
    • We don't known number boundaries

      var num = 123456789L;
      var len = 0;
      var tmp = 1L;
      while(tmp < num)
      {
          len++;
          tmp = (tmp << 3) + (tmp << 1);
      }
      

    This algorithm, should have speed comparable to for-loop (2) provided, but a bit faster due to (2 bit-shifts, add and subtract, instead of division).

    As for Log10 algorithm, it will give you only approximate answer (that is close to real, but still), since analytic formula for computing Log function have infinite loop and can't be calculated precisely Wiki.

提交回复
热议问题