How in Java do you return the first digit of an integer.?
i.e.
345
Returns an int of 3.
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?
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;
}