How in Java do you return the first digit of an integer.?
i.e.
345
Returns an int of 3.
public static int firstDigit(int n) {
while (n < -9 || 9 < n) n /= 10;
return Math.abs(n);
}
Should handle negative numbers pretty well, too. Will return a negative first digit in that case.
public static void firstDigit(int number){
while(number != 0){
if (number < 10){
System.out.println("The first digit is " + number);
}
number = number/10;
}
}
When you call it, you can use Maths.abs in order for it to work for negative number:
firstDigit(Math.abs(9584578));
This returns 9
Yet another way:
public int firstDigit(int x) {
if (x == 0) return 0;
x = Math.abs(x);
return (int) Math.floor(x / Math.pow(10, Math.floor(Math.log10(x))));
}
I find this one more simpler:
int firstDigit(int num)
{
if(num/10 == 0)
return num;
return firstDigit(num/10);
}
int firstNumber(int x){
int firstN = x;
while(firstN > 9){
firstN = (firstN - (firstN%10))/10;
}
return firstN;
}