M
Martin Gregorie
Tim said:user said:say i got an int, 530: what could i do to get back 2nd digit [the 3 in
this case]?
If N is the variable with the int, and you are counting from the right, then
you could try this:
(N/10)%10
Similarly, (N/100)%10 would be the 5, and (N/1)%10 would be the 0.
Thats asking to be generalized as:
/**
* Return the nth digit from value. Digits are counted from the right.
* The rightmost digit is zero. -1 is returned of n doesn't reference
* a digit within the number.
*/
int getDigit(int value, int n)
{
int i = 1;
int digit = -1;
value = Maths.abs(value);
if (n >= 0)
{
while ((value/(10*i) > 0)
i++;
digit = (n >= i ? -1 : value/(10*n)%10);
}
return digit;
}
The absolute value is only required for the range test on n to work.