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, eg32 % 10
returns2
Integer division drops remainders, eg
32 / 10
returns3
.