Search code examples
javanumber-manipulation

Return the nth digit of a number


public class Return {    
    public static void main(String[] args) {        
        int answer = digit(9635, 1);
        print("The answer is " + answer);
    }

    static void print(String karen) {
        System.out.println (karen);
    }

    static int digit(int a, int b) {
        int digit = a;
        return digit;
    }     
}

Create a program that uses a function called digit which returns the value of the nth digit from the right of an integer argument. The value of n should be a second argument.

For Example: digit(9635, 1) returns 5 and digit(9635, 3) returns 6.


Solution

  • Without spoon-feeding you the code:

    The nth digit is the remainder after dividing (a divided by 10b-1) by 10.

    int digit(int a, int b) {
    return a / (int)Math.pow(10, b - 1) % 10;
    }
    See live demo.


    If you want an iterative approach:

    Loop b-1 times, each time assigning to the a variable the result of dividing a by 10.
    After looping, the nth digit is the remainder of dividing a by 10.

    int digit(int a, int b) {
    while (--b > 0) {
    a /= 10;
    }
    return a % 10;
    }
    See live demo.


    Relevant facts about Java:

    • The modulo operator % returns the remainder after division, eg 32 % 10 returns 2

    • Integer division drops remainders, eg 32 / 10 returns 3.