2

What methods can I employ to return a specific digit of an integer?

//val = number to find target digit on
//dig = the digit to return from right-side
private int digit(int val, int dig) {
    String num = "" + val;
    return Character.getNumericValue(num.charAt(num.length-dig));
}

For example, if val were "48602" and I wanted to grab the 2nd digits (tenths), it would return "0".

Here's an ugly way to do it, but is there a way without using strings at all? Perhaps with modulo? What if I wanted to find the 7th digit (millionths), this method wouldn't even work (the number would have to be parsed as "0048602").

Potential use would be for a Radix sort (putting numbers into "buckets" based on significant digits). I'm finding using this method is relatively taxing.

gator
  • 3,465
  • 8
  • 36
  • 76

3 Answers3

2

There is an idea

private int digit(int val,int dig){
    int div = 1;
    for(int i=0;i<dig;i++)
        div*=10; //make 10^dig
    val/=div; //remove the smaller digits
    return val%10; //return only one digit
}

Not tested

EDIT better way:

private int digit(int val,int dig){
    int div = (int)Math.pow(10,dig);
    val/=div; //remove the smaller digits
    return val%10; //return only one digit
}
maskacovnik
  • 3,080
  • 5
  • 20
  • 26
2

You can do it with the following code:

public int getDigit(int n, int i) {    
    return (n / ((int) Math.pow(10, i))) % 10;
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
2

You could use

    return ((val%(Math.pow(10, dig))) - (val%(Math.pow(10, dig-1))))/(Math.pow(10, dig-1));

Where

(val%(Math.pow(10, dig)))

takes off the front digits

- (val%(Math.pow(10, dig-1)))

subtracts the trailing digits, and

/(Math.pow(10, dig-1)

takes off the remaining zeros

Olivier Poulin
  • 1,778
  • 8
  • 15