Return first digit of an integer

后端 未结 23 1784
醉梦人生
醉梦人生 2020-11-28 13:12

How in Java do you return the first digit of an integer.?

i.e.

345

Returns an int of 3.

23条回答
  •  北海茫月
    2020-11-28 13:53

    I think this might be a nice way to do that:

    public static int length(int number) {
        return (int)Math.log10(Math.abs(number)) + 1;
    }
    
    public static int digit(int number, int digit) {
        for (int i = 0; i < digit; i++) {
            number /= 10;
        }
        return Math.abs(number % 10);
    }
    

    Works for both negative and positive numbers. digit(345, length(345) - 1) will return 3, digit(345, 0) will return 5 e.g. and so on...

提交回复
热议问题