views:

207

answers:

6

Hi, 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 = ????
+3  A: 
    int number = 534;
    int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));
reverendgreen
thanks for that!
Michoel
you're welcome.
reverendgreen
A: 

Integer.parseInt will take a string and return a int.

unholysampler
thank you for the tip!
Michoel
A: 
int firstDigit = Integer.parseInt(Character.toString(firstLetterChar));
Adamski
A: 
int number = 534;
String numberString = "" + number;
char firstLetterchar = numberString.charAt(0);
int firstDigit = Integer.parseInt("" + firstLetterChar);
Adam
is there a reason why you prefer to do numberString = "" + number instead of numberString = Integer.toString(number)?
Michoel
He is just lazy to type the whole thing :)
Dimitris Andreou
@Dimitris True. :) But "" + int = String is a Java idiom
Adam
And ""+int is a very clumsy idiom. It creates a StringBuilder, appends an empty string to it, converts the int to a string, appends this string to the StringBuilder, the converts the StringBuilder to a String. It's much more efficient to just say Integer.toString(n) or String.valueOf(n).
Jay
+1  A: 
firstDigit = number/((int)(pow(10,(int)log(number)));

This should get your first digit using math instead of strings.

In your example log(543) = 2.73 which casted to an int is 2. pow(10, 2) = 100 543/100 = 5.43 but since it's an int it gets truncated to 5

Ben Burnett
would be interesting to see how that benchmarks against string operations
Arkadiy
looks like fun but are there any advantages to doing it this way? if i was reading that line and im not a maths professor i would have no idea what it does :-)
Michoel
Well, the log of 100 is 2 and the log of 999 is 2.99 so you can see that the log is returning the number of digits minus one if stored as an int. Number of digits tells you what to divide the number by. Then we use the built in power of int to truncate everything after the decimal leaving us with the first digit.I can't tell you which way is faster though. I just wanted to offer an alternative solution that doesn't require converting the number to a string.
Ben Burnett
Math.pow is so inefficient for ints though; you should roll your own there.
Vuntic
readability is not archived. beside that you got one nice row :)
starcorn
+6  A: 

Almost certainly more efficient than using Strings:

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

(Works only for nonnegative integers.)

Sean
Nice, a clean non-String approach
Steve Kuo