Finding the number of digits of an integer

前端 未结 17 2043
难免孤独
难免孤独 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 16:56

    You can obviously eliminate the method 1 from the competition, because the atoi/toString algorithm it uses would be similar to method 2.

    Method 3's speed depends on whether the code is being compiled for a system whose instruction set includes log base 10.

    0 讨论(0)
  • 2020-12-07 16:56

    Keep it simple:

    long long int a = 223452355415634664;
    
    int x;
    for (x = 1; a >= 10; x++)
    {
       a = a / 10;
    }
    
    printf("%d", x);
    
    0 讨论(0)
  • 2020-12-07 17:07

    Test conditions

    • Decimal numeral system
    • Positive integers
    • Up to 10 digits
    • Language: ActionScript 3

    Results

    digits: [1,10],

    no. of runs: 1,000,000

    random sample: 8777509,40442298,477894,329950,513,91751410,313,3159,131309,2

    result: 7,8,6,6,3,8,3,4,6,1

    CONVERSION TO STRING: 724ms

    LOGARITMIC CALCULATION: 349ms

    DIV 10 ITERATION: 229ms

    MANUAL CONDITIONING: 136ms

    Note: Author refrains from making any conclusions for numbers with more than 10 digits.


    Script

    package {
        import flash.display.MovieClip;
        import flash.utils.getTimer;
        /**
         * @author Daniel
         */
        public class Digits extends MovieClip {
            private const NUMBERS : uint = 1000000;
            private const DIGITS : uint = 10;
    
            private var numbers : Array;
            private var digits : Array;
    
            public function Digits() {
                // ************* NUMBERS *************
                numbers = [];
                for (var i : int = 0; i < NUMBERS; i++) {
                    var number : Number = Math.floor(Math.pow(10, Math.random()*DIGITS));
                    numbers.push(number);
                }   
                trace('Max digits: ' + DIGITS + ', count of numbers: ' + NUMBERS);
                trace('sample: ' + numbers.slice(0, 10));
    
                // ************* CONVERSION TO STRING *************
                digits = [];
                var time : Number = getTimer();
    
                for (var i : int = 0; i < numbers.length; i++) {
                    digits.push(String(numbers[i]).length);
                }
    
                trace('\nCONVERSION TO STRING - time: ' + (getTimer() - time));
                trace('sample: ' + digits.slice(0, 10));
    
                // ************* LOGARITMIC CALCULATION *************
                digits = [];
                time = getTimer();
    
                for (var i : int = 0; i < numbers.length; i++) {
                    digits.push(Math.floor( Math.log( numbers[i] ) / Math.log(10) ) + 1);
                }
    
                trace('\nLOGARITMIC CALCULATION - time: ' + (getTimer() - time));
                trace('sample: ' + digits.slice(0, 10));
    
                // ************* DIV 10 ITERATION *************
                digits = [];
                time = getTimer();
    
                var digit : uint = 0;
                for (var i : int = 0; i < numbers.length; i++) {
                    digit = 0;
                    for(var temp : Number = numbers[i]; temp >= 1;)
                    {
                        temp/=10;
                        digit++;
                    } 
                    digits.push(digit);
                }
    
                trace('\nDIV 10 ITERATION - time: ' + (getTimer() - time));
                trace('sample: ' + digits.slice(0, 10));
    
                // ************* MANUAL CONDITIONING *************
                digits = [];
                time = getTimer();
    
                var digit : uint;
                for (var i : int = 0; i < numbers.length; i++) {
                    var number : Number = numbers[i];
                    if (number < 10) digit = 1;
                    else if (number < 100) digit = 2;  
                    else if (number < 1000) digit = 3;  
                    else if (number < 10000) digit = 4;  
                    else if (number < 100000) digit = 5;  
                    else if (number < 1000000) digit = 6;  
                    else if (number < 10000000) digit = 7;  
                    else if (number < 100000000) digit = 8;  
                    else if (number < 1000000000) digit = 9;  
                    else if (number < 10000000000) digit = 10;  
                    digits.push(digit);
                }
    
                trace('\nMANUAL CONDITIONING: ' + (getTimer() - time));
                trace('sample: ' + digits.slice(0, 10));
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-07 17:07
    • conversion to string: This will have to iterate through each digit, find the character that maps to the current digit, add a character to a collection of characters. Then get the length of the resulting String object. Will run in O(n) for n=#digits.

    • for-loop: will perform 2 mathematical operation: dividing the number by 10 and incrementing a counter. Will run in O(n) for n=#digits.

    • logarithmic: Will call log10 and floor, and add 1. Looks like O(1) but I'm not really sure how fast the log10 or floor functions are. My knowledge of this sort of things has atrophied with lack of use so there could be hidden complexity in these functions.

    So I guess it comes down to: is looking up digit mappings faster than multiple mathematical operations or whatever is happening in log10? The answer will probably vary. There could be platforms where the character mapping is faster, and others where doing the calculations is faster. Also to keep in mind is that the first method will creats a new String object that only exists for the purpose of getting the length. This will probably use more memory than the other two methods, but it may or may not matter.

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

    Use the simplest solution in whatever programming language you're using. I can't think of a case where counting digits in an integer would be the bottleneck in any (useful) program.

    C, C++:

    char buffer[32];
    int length = sprintf(buffer, "%ld", (long)123456789);
    

    Haskell:

    len = (length . show) 123456789
    

    JavaScript:

    length = String(123456789).length;
    

    PHP:

    $length = strlen(123456789);
    

    Visual Basic (untested):

    length = Len(str(123456789)) - 1
    
    0 讨论(0)
  • 2020-12-07 17:09
    import math
    def numdigits(n):
        return ( int(math.floor(math.log10(n))) + 1 )
    
    0 讨论(0)
提交回复
热议问题