Search code examples
javadigitradix-sort

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.


Solution

  • 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
    }