Way to get number of digits in an int?

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

提交回复
热议问题