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 = ????
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.
firstDigit = number/((int)(pow(10,(int)log(number)))); This should get your first digit using math instead of strings.
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.
Almost certainly more efficient than using Strings:
int firstDigit(int x) { while (x > 9) { x /= 10; } return x; }
(Works only for nonnegative integers.)
int number = 534; int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
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