Modular arithmetic can be used to accomplish what you want. For example, if you divide 123
by 10
, and take the remainder, you'd get the first digit 3
. If you do integer division of 123
by 100
and then divide the result by 10
, you'd get the second digit 2
. More generally, the n
-th digit of a number can be obtained by the formula (number / base^(n-1)) % base
:
public int getNthDigit(int number, int base, int n) {
return (int) ((number / Math.pow(base, n - 1)) % base);
}
System.out.println(getNthDigit(123, 10, 1)); // 3
System.out.println(getNthDigit(123, 10, 2)); // 2
System.out.println(getNthDigit(123, 10, 3)); // 1