How in Java do you return the first digit of an integer.?
i.e.
345
Returns an int of 3.
This is Groovy, but it should be easy to convert to Java:
int firstNum(int x) {
a = Math.abs(x)
sig = Math.floor(Math.log10(a))
return a / Math.pow(10, sig)
}
Results:
groovy> println(firstNum(345))
3groovy> println(firstNum(3452))
3groovy> println(firstNum(-112))
1groovy> println(firstNum(9999))
9groovy> println(firstNum(Integer.MAX_VALUE))
2groovy> println(firstNum(Integer.MIN_VALUE + 1))
2
//Try this one.
Scanner input = new Scanner(System.in);
System.out.println("enter first 9 digits: ");
String x = input.nextLine();
String x1 = x.substring(0,1);
int d1 = Integer.parseInt(x1);
System.out.println(d1);
// the substring gives the position of extraction. method dont seem to work for letters though
Looking at the code supplied it seems a tad over complicating the whole thing, here is a simple solution...
int number = 4085;
int firstDigit = number;
while (firstDigit > 9)
{
firstDigit = firstDigit / 10;
}
System.out.println("The First Digit is " + firstDigit);
Homework Hint: Convert it to a string and and return the first character.
Here is a smaller version to get digits of all positions, it works with negative value (not decimal).
int number = -23456;
int length = (int) Math.log10(Math.abs(number)) + 1; //This gets the length of the number of digits used
//Math.abs to change negative int to positive
System.out.println("Digit at pos " + 1 + " is :- " + (int)(Math.abs(number)/Math.pow(10,(length-1))));
for (int i = 2; i <= length; i++){
System.out.println("Digit at pos " + i + " is :- " + (int)(Math.abs(number)/Math.pow(10,(length-i))%10));
}
I think more simple to do :
int firstDigit = i-(i/10)*10 // i is an integer or long value, positive or negative.