How in Java do you return the first digit of an integer.?
i.e.
345
Returns an int of 3.
To finding first digit of a number is little expensive than last digit. To find first digit of a number we divide the given number by 10 until number is greater than 10. At the end we are left with the first digit.
To get the first digit, we can use the Python math log10() function. In the loop example, we divided by 10 until we got to a number between 0 and 10. By using the log10() function, we can find out exactly how many times we need to divide by 10 and then do the division directly.
The first digit 1 is in the Hundreds place and has a value of One hundred. The second digit 1 is in the Tens place and has a value of Ten. The digit 2 is in the Ones place and has a value of Two.
The easiest way would be to use String.valueOf(Math.abs((long)x)).charAt(0)
- that will give it you as a char
1. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With