Finding the number of digits of an integer

前端 未结 17 2198
难免孤独
难免孤独 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

    You can use a recursive solution instead of a loop, but somehow similar:

    @tailrec
    def digits (i: Long, carry: Int=1) : Int =  if (i < 10) carry else digits (i/10, carry+1)
    
    digits (8345012978643L)
    

    With longs, the picture might change - measure small and long numbers independently against different algorithms, and pick the appropriate one, depending on your typical input. :)

    Of course nothing beats a switch:

    switch (x) {
      case 0:  case 1:  case 2:  case 3:  case 4:  case 5:  case 6:  case 7:  case 8:  case 9: return 1;
      case 10: case 11: // ...
      case 99: return 2;
      case 100: // you get the point :) 
      default: return 10; // switch only over int
    }
    

    except a plain-o-array:

       int [] size = {1,1,1,1,1,1,1,1,1,2,2,2,2,2,... };
       int x = 234561798;
       return size [x];
    

    Some people will tell you to optimize the code-size, but yaknow, premature optimization ...

提交回复
热议问题