Return first digit of an integer

Viewed 84054

How in Java do you return the first digit of an integer.?

i.e.

345

Returns an int of 3.

25 Answers

The easiest way would be to use String.valueOf(Math.abs((long)x)).charAt(0) - that will give it you as a char1. To get that as an integer value, you could just subtract '0' (as in Unicode, '0' to '9' are contiguous).

It's somewhat wasteful, of course. An alternative would just be to take the absolute value, then loop round dividing by 10 until the number is in the range 0-9. If this is homework, that's the answer I'd give. However, I'm not going to provide the code for it because I think it might be homework. However, if you provide comments and edit your answer to explain how you're doing and what problems you're running into, we may be able to help.


1One sticky point to note is that the absolute value of Integer.MIN_VALUE can't be represented as an int - so you may should first convert to a long, then use Math.abs, then do arithmetic. That's why there's a cast there.

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))));
}
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.

Ignoring negative values leads to:

(""+345).charAt(0);

The missing recursive solution:

int getFirstInt(int input) {
  if (input > 0 ? input < 10 : input > -10) {
    return input > 0 ? input : -input;
  }
  return getFirstInt(input / 10);
}

I wouldn't use the ternary operator in real life but - isn't it kind of beautiful? ;)

Updated: log10 solution:

A variation on the log10 solution with no division.:

public int getFirstDigit(int x) {
    double e = Math.log10(Math.abs((long) x));
    return Double.valueOf(Math.pow(10.0, e - Math.floor(e))).intValue());
}

What's it doing?

  1. cast the int to long (to handle the MIN_VALUE issue)
  2. get the absolute value
  3. calculate the log10
  4. calculate the floor of the log10
  5. subtract the floor from the log10 (the difference will be the fraction)
  6. raise ten to the difference, giving you the value of the first digit.

while loop solution:

To handle Integer.MIN_VALUE and keep Math.abs() and the cast to long out of the loop:

public static int getFirstDigit(int i) {
    i = Math.abs(i / (Math.abs((long)i) >= 10 ) ? 10 : 1);
    while (i >= 10 ) 
        i /= 10;
    return i;
}

Homework Hint: Convert it to a string and and return the first character.

Fastest way would be :

  • Compute log of the abs(x), then get floor. Let's call it n.
  • Divide the number with 10^n
int main(void) {
  int num = 3421;

  while (num*num + 10 - num*(1 + num) <= 0) {
    num *= (num - 0.9*num)/num;
  }

  std::cout << num << std::endl;
}
int a = 354;
int b = (int)(a / Math.Pow(10, (int)Math.Log10(a))); // 3
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

Its easier then any solution given hier if you only need the first digit/one sepcific digit:

int temp = 345%100 //temp = 45
int firstDigit = (345 -temp)/100 //fisrtDigit= 300/100 = 3

If you need to check the 2nd digit too then you need to repeat step one

 int tempHuns = 345%100 //tempHuns = 45  
 tempTens = tempHuns %10 // tempTens= 5
 int secondDigit = (tempHuns - tempTens)/10 //fisrtDigit= 40/10 = 4

try this:

 public static int getFirstDigit(int a){
    int firstDigit = a / 10;
        if(firstDigit > 10)return getFirstDigit(firstDigit);
        else if (firstDigit == 0)return a;
        else return firstDigit;
}

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))
3

groovy> println(firstNum(3452))
3

groovy> println(firstNum(-112))
1

groovy> println(firstNum(9999))
9

groovy> println(firstNum(Integer.MAX_VALUE))
2

groovy> 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

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));
}

To separate digits of an integer from left to right I use 2 different methods, the first one to count how many digits the integer is made up of and then I split them from left to right by dividing the integer by 10 raised to the power of the number of digits minus 1.

//method to separate digits of an integer from left to right
private static void separateDigits(int num){
    int numOfDigits = countNumberOfDigits(num);
    for (int numOfZeros = numOfDigits-1; numOfZeros >= 0 ; --numOfZeros){
        int divisor = (int) Math.pow(10, numOfZeros);
        System.out.print( Math.abs(num) / divisor + " // " );
        num %= divisor;
    }
}

//method to count number of digits
private static int countNumberOfDigits(int num){
    int numOfDigits=0;
    //using absolute value of num allows method to work even with negative integers
    while(Math.abs(num) > 0){ 
        num = num / 10;
        numOfDigits++; //this counts the number of times the "while" loops
    }
    return numOfDigits;
}

No use of Arrays or recursive methods just simple division with "/" and "%".

Invoking the method:

public static void main(String args[]) {

separateDigits( -123456789 );

}

yields: 1 // 2 // 3 // 4 // 5 // 6 // 7 // 8 // 9 //

I think more simple to do :

int firstDigit = i-(i/10)*10 // i is an integer or long value, positive or negative.

This way worked for me just fine, but it does involve converting from int to string and back to int.

Integer.parseInt(String.valueOf(x).substring(0,1));
Related