I am having my final exam tomorrow so i am practicing some questions.But i am stuck at this question.
Write a method named getNthDigit that returns the n-th digit of an integer.It should work for negative numbers as well.
Eg.
CALL VALUE RETURNED
getNthDigit(123,1) 3
getNthDigit(123,2) 2
getNthDigit(123,3) 1
getNthDigit(-123,1) 3
My code:
public static void getNthDigit(int x,int y){
x=Math.abs(x);
x%10;
}
My thought process is everytime i modulo it by 10,it gives me the last digit.But it is still wrong.Like if i call for getNthDigit(123,2) ,i no longer need the last digit value.
Modular arithmetic can be used to accomplish what you want. For example, if you divide
123
by10
, and take the remainder, you'd get the first digit3
. If you do integer division of123
by100
and then divide the result by10
, you'd get the second digit2
. More generally, the n-th digit of a number can be obtained by the formula(number / base^(n-1)) % base:
Hope it helps.
Instead of strings, you could do:
abs(n)
takes care of the negative case.n / 10^(y - 1)
truncatesn
to the first (counting from the left)y
digits.% 10
gets the last digit of that resulting number.Why not simply convert the number to string and then get the character at the required position ?
I'd write it into a string, strip off any leading -ve and then just index into the string (handling the fact you want 1 based indexes where Java uses 0 based).
Try this: