Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving the first digit of a number [duplicate]

I am just learning Java and am trying to get my program to retrieve the first digit of a number - for example 543 should return 5, etc. I thought to convert to a string, but I am not sure how I can convert it back? Thanks for any help.

int number = 534; String numberString = Integer.toString(number); char firstLetterChar = numberString.charAt(0); int firstDigit = ???? 
like image 242
Michoel Avatar asked Jun 03 '10 16:06

Michoel


People also ask

How do you extract the first digit of a number?

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 isolate the first digit of a number in Java?

firstDigit = number/((int)(pow(10,(int)log(number)))); This should get your first digit using math instead of strings.

How do you extract the first digit of a number 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.


2 Answers

Almost certainly more efficient than using Strings:

int firstDigit(int x) {     while (x > 9) {         x /= 10;     }     return x; } 

(Works only for nonnegative integers.)

like image 54
Sean Avatar answered Sep 23 '22 02:09

Sean


    int number = 534;     int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1)); 
like image 36
Jordan Allan Avatar answered Sep 23 '22 02:09

Jordan Allan