Finding the number of digits of an integer

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

    0 讨论(0)
  • 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 ...

    0 讨论(0)
  • 2020-12-07 17:10

    log(x,n)-mod(log(x,n),1)+1

    Where x is a the base and n is the number.

    0 讨论(0)
  • 2020-12-07 17:14

    For very large integers, the log method is much faster. For instance, with a 2491327 digit number (the 11920928th Fibonacci number, if you care), Python takes several minutes to execute the divide-by-10 algorithm, and milliseconds to execute 1+floor(log(n,10)).

    0 讨论(0)
  • 2020-12-07 17:14

    I was curious after seeing @daniel.sedlacek results so I did some testing using Swift for numbers having more than 10 digits. I ran the following script in the playground.

    let base = [Double(100090000000), Double(100050000), Double(100050000), Double(100000200)]
    var rar = [Double]()
    for i in 1...10 {
        for d in base {
            let v = d*Double(arc4random_uniform(UInt32(1000000000)))
            rar.append(v*Double(arc4random_uniform(UInt32(1000000000))))
            rar.append(Double(1)*pow(1,Double(i)))
        }
    }
    
    print(rar)
    
    var timeInterval = NSDate().timeIntervalSince1970
    
    for d in rar {
        floor(log10(d))
    }
    
    var newTimeInterval = NSDate().timeIntervalSince1970
    
    print(newTimeInterval-timeInterval)
    
    
    timeInterval = NSDate().timeIntervalSince1970
    for d in rar {
        var c = d
        while c > 10 {
            c = c/10
        }
    }
    
    newTimeInterval = NSDate().timeIntervalSince1970
    
    print(newTimeInterval-timeInterval)
    

    Results of 80 elements

    0.105069875717163 for floor(log10(x))
    0.867973804473877 for div 10 iterations

    0 讨论(0)
提交回复
热议问题