Way to get number of digits in an int?

后端 未结 30 1274
梦毁少年i
梦毁少年i 2020-11-22 17:21

Is there a neater way for getting the number of digits in an int than this method?

int numDigits = String.valueOf(1000).length();
30条回答
  •  不要未来只要你来
    2020-11-22 17:26

    Curious, I tried to benchmark it ...

    import org.junit.Test;
    import static org.junit.Assert.*;
    
    
    public class TestStack1306727 {
    
        @Test
        public void bench(){
            int number=1000;
            int a= String.valueOf(number).length();
            int b= 1 + (int)Math.floor(Math.log10(number));
    
            assertEquals(a,b);
            int i=0;
            int s=0;
            long startTime = System.currentTimeMillis();
            for(i=0, s=0; i< 100000000; i++){
                a= String.valueOf(number).length();
                s+=a;
            }
            long stopTime = System.currentTimeMillis();
            long runTime = stopTime - startTime;
            System.out.println("Run time 1: " + runTime);
            System.out.println("s: "+s);
            startTime = System.currentTimeMillis();
            for(i=0,s=0; i< 100000000; i++){
                b= number==0?1:(1 + (int)Math.floor(Math.log10(Math.abs(number))));
                s+=b;
            }
            stopTime = System.currentTimeMillis();
            runTime = stopTime - startTime;
            System.out.println("Run time 2: " + runTime);
            System.out.println("s: "+s);
            assertEquals(a,b);
    
    
        }
    }
    

    the results are :

    Run time 1: 6765
    s: 400000000
    Run time 2: 6000
    s: 400000000
    

    Now I am left to wonder if my benchmark actually means something but I do get consistent results (variations within a ms) over multiple runs of the benchmark itself ... :) It looks like it's useless to try and optimize this...


    edit: following ptomli's comment, I replaced 'number' by 'i' in the code above and got the following results over 5 runs of the bench :

    Run time 1: 11500
    s: 788888890
    Run time 2: 8547
    s: 788888890
    
    Run time 1: 11485
    s: 788888890
    Run time 2: 8547
    s: 788888890
    
    Run time 1: 11469
    s: 788888890
    Run time 2: 8547
    s: 788888890
    
    Run time 1: 11500
    s: 788888890
    Run time 2: 8547
    s: 788888890
    
    Run time 1: 11484
    s: 788888890
    Run time 2: 8547
    s: 788888890
    

提交回复
热议问题