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