Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return first digit of an integer

Tags:

java

int

How in Java do you return the first digit of an integer.?

i.e.

345

Returns an int of 3.

like image 959
Tony Avatar asked Jan 12 '10 19:01

Tony


People also ask

How do you find the first digit of an integer?

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.

How do you get the first digit of an int in Python?

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.

Where is the first digit in a number?

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.


1 Answers

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.

like image 148
Jon Skeet Avatar answered Oct 07 '22 16:10

Jon Skeet