Return first digit of an integer

The easiest way would be to use String.valueOf(Math.abs((long)x)).charAt(0) – that will give it you as a char1. To get that as an integer value, you could just subtract ‘0’ (as in Unicode, ‘0’ to ‘9’ are contiguous).

It’s somewhat wasteful, of course. An alternative would just be to take the absolute value, then loop round dividing by 10 until the number is in the range 0-9. If this is homework, that’s the answer I’d give. However, I’m not going to provide the code for it because I think it might be homework. However, if you provide comments and edit your answer to explain how you’re doing and what problems you’re running into, we may be able to help.


1One sticky point to note is that the absolute value of Integer.MIN_VALUE can’t be represented as an int – so you may should first convert to a long, then use Math.abs, then do arithmetic. That’s why there’s a cast there.

Leave a Comment