Get a specific digit of a number from an int in Java
35,266
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
Author by
dualCore
I love discovering new programming lauguages, and working with robots!
Updated on February 13, 2020Comments
-
dualCore over 4 years
Possible Duplicate:
Return first digit of an integerIn my java program, I store a number in an array.
p1Wins[0] = 123;
How would I check the first digit of
p1Wins[0]
? Or the second or third? I just need to be able to find the value of any specific digit.Thanks!
-
Greg Hewgill over 12 yearsI don't think you want to use exclusive-or (
^
) there. -
zellio over 12 years@GregHewgill - haha yeah, sorry I prototyped the function in psudeo code and then suddenly couldn't remember the
Math.pow
function so I had to go look it up.