gator
gator

Reputation: 3523

Find target digit of an integer

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.

Upvotes: 2

Views: 428

Answers (3)

Olivier Poulin
Olivier Poulin

Reputation: 1796

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

Upvotes: 2

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

You can do it with the following code:

public int getDigit(int n, int i) {    
    return (n / ((int) Math.pow(10, i))) % 10;
}

Upvotes: 2

maskacovnik
maskacovnik

Reputation: 3084

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
}

Upvotes: 2

Related Questions