Way to get number of digits in an int?

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

提交回复
热议问题