Return first digit of an integer

后端 未结 23 1802
醉梦人生
醉梦人生 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条回答
  •  Happy的楠姐
    2020-11-28 13:58

    Updated: log10 solution:

    A variation on the log10 solution with no division.:

    public int getFirstDigit(int x) {
        double e = Math.log10(Math.abs((long) x));
        return Double.valueOf(Math.pow(10.0, e - Math.floor(e))).intValue());
    }
    

    What's it doing?

    1. cast the int to long (to handle the MIN_VALUE issue)
    2. get the absolute value
    3. calculate the log10
    4. calculate the floor of the log10
    5. subtract the floor from the log10 (the difference will be the fraction)
    6. raise ten to the difference, giving you the value of the first digit.

    while loop solution:

    To handle Integer.MIN_VALUE and keep Math.abs() and the cast to long out of the loop:

    public static int getFirstDigit(int i) {
        i = Math.abs(i / (Math.abs((long)i) >= 10 ) ? 10 : 1);
        while (i >= 10 ) 
            i /= 10;
        return i;
    }
    

提交回复
热议问题