Question

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.

Was it helpful?

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.

OTHER TIPS

static int dig(int a, int b) {
    int i, digit=1;
    for(i=b-1; i>0; i++)
        digit = digit*10;
    digit = (a/digit) % 10;
    return digit;
 }

The other way is convert the digit into array and return the nth index

static char digit(int a,int b)
    {
        String x=a+"";
        char x1[]=x.toCharArray();
        int length=x1.length;
        char result=x1[length-b];
        return result;
    }

Now run from your main method like this way

System.out.println("digit answer  "+digit(1254,3));

output

digit answer  2

Convert number to string and then use the charAt() method.

class X{   
    static char digit(int a,int n)
    {
        String x=a+"";
        return x.charAt(n-1); 
    }

    public static void main(String[] args) {
        System.out.println(X.digit(123, 2));
    }
}

You may want to double check that the nth position is within the length of the number:

static char digit(int a, int n) {
    String x = a + "";
    char digit='\0' ;
    if (n > 0 && n <= x.length()) {
        digit = x.charAt(n - 1);
    }
    return digit;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top