Can anyone enlighten me on how to retrieve the nth digit of an integer, without treating the integer as a string. Just purely using for or while loop, and starting from the left.
So for example if the integer is 2345,
when I enter position 1; it should return 2,
position 2 should return 3, so on and so forth.
I really have no idea how to tackle this question.. Please help. Thank you
I did some code below but I know it is wrong.
import java.util.*;
class FindAnyDigit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a positive integer: ");
int integer = sc.nextInt();
System.out.println("Enter the position where you wish to retrieve the digit: ");
int position = sc.nextInt();
int multiple = 1;
int digit = 1;
for (int i = 1; i <= position; i++) {
multiple = multiple * 10;
while (integer > multiple) {
digit = integer % 10;
integer = integer / 10;
}
}
System.out.println("The digit at " + position +
" position is " + digit);
}
}