Way to get number of digits in an int?

后端 未结 30 933
梦毁少年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:46

    simple solution:

    public class long_length {
        long x,l=1,n;
        for (n=10;n<x;n*=10){
            if (x/n!=0){
                l++;
            }
        }
        System.out.print(l);
    }
    
    0 讨论(0)
  • 2020-11-22 17:46

    I wrote this function after looking Integer.java source code.

    private static int stringSize(int x) {
        final int[] sizeTable = {9, 99, 999, 9_999, 99_999, 999_999, 9_999_999,
                99_999_999, 999_999_999, Integer.MAX_VALUE};
        for (int i = 0; ; ++i) {
            if (x <= sizeTable[i]) {
                return i + 1;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:47

    Another string approach. Short and sweet - for any integer n.

    int length = ("" + n).length();
    
    0 讨论(0)
  • 2020-11-22 17:47

    Marian's Solution, now with Ternary:

     public int len(int n){
            return (n<100000)?((n<100)?((n<10)?1:2):(n<1000)?3:((n<10000)?4:5)):((n<10000000)?((n<1000000)?6:7):((n<100000000)?8:((n<1000000000)?9:10)));
        }
    

    Because we can.

    0 讨论(0)
  • 2020-11-22 17:47

    Easy recursive way

    int    get_int_lenght(current_lenght, value)
    {
     if (value / 10 < 10)
        return (current_lenght + 1);
    return (get_int_lenght(current_lenght + 1, value))
    }
    

    not tested

    0 讨论(0)
  • 2020-11-22 17:48

    With design (based on problem). This is an alternate of divide-and-conquer. We'll first define an enum (considering it's only for an unsigned int).

    public enum IntegerLength {
        One((byte)1,10),
        Two((byte)2,100),
        Three((byte)3,1000),
        Four((byte)4,10000),
        Five((byte)5,100000),
        Six((byte)6,1000000),
        Seven((byte)7,10000000),
        Eight((byte)8,100000000),
        Nine((byte)9,1000000000);
    
        byte length;
        int value;
    
        IntegerLength(byte len,int value) {
            this.length = len;
            this.value = value;
        }
    
        public byte getLenght() {
            return length;
        }
    
        public int getValue() {
            return value;
        }
    }
    

    Now we'll define a class that goes through the values of the enum and compare and return the appropriate length.

    public class IntegerLenght {
        public static byte calculateIntLenght(int num) {    
            for(IntegerLength v : IntegerLength.values()) {
                if(num < v.getValue()){
                    return v.getLenght();
                }
            }
            return 0;
        }
    }
    

    The run time of this solution is the same as the divide-and-conquer approach.

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