IN JAVA Write a method nthDigitBack which takes in two ints, n and num. This met
ID: 3729759 • Letter: I
Question
IN JAVA Write a method nthDigitBack which takes in two ints, n and num. This method finds the n th lowest order digit in num. In other words, nthDigitBack returns the n th digit from the right. The rightmost digit is considered the 0 th digit back. nthDigitBack should evaluate to 0 for digits out of range (so if you ask for the 1000th digit back of 7546, nthDigitBack will return 0). Here are some example method calls of nthDigitBack:
• nthDigitBack(0,123) 3
• nthDigitBack(1,123) 2
• nthDigitBack(2,123) 1
• nthDigitBack(3,123) 0 •
nthDigitBack(0,0) 0 •
nthDigitBack(3,18023) 8
Explanation / Answer
public class MainClass {
public static int nthDigitBack(int n,int num){
int result=0;
for(int i=0;i<=n;i++){
result=num%10;
num=num/10;
if(num==0 && i!=n)
{
result=0;
break;
}
}
return result;
}
public static void main(String[] args) {
System.out.println(nthDigitBack(0,123));
System.out.println(nthDigitBack(1,123));
System.out.println(nthDigitBack(2,123));
System.out.println(nthDigitBack(3,123));
System.out.println(nthDigitBack(0,0));
System.out.println(nthDigitBack(3,18023));
}
}