Last nth digit of an integer

2020-08-04 10:37发布

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.

标签: java
5条回答
在下西门庆
2楼-- · 2020-08-04 10:53

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

Hope it helps.

查看更多
\"骚年 ilove
3楼-- · 2020-08-04 10:57

Instead of strings, you could do:

(Math.abs(x) / Math.pow(10, y - 1)) % 10
  • abs(n) takes care of the negative case.
  • n / 10^(y - 1) truncates n to the first (counting from the left) y digits.
  • % 10 gets the last digit of that resulting number.
查看更多
Evening l夕情丶
4楼-- · 2020-08-04 11:00

Why not simply convert the number to string and then get the character at the required position ?

public static void getNthDigit(int x,int y){
    String str = String.valueOf(x);
    if(str.charAt(0) == '-')
        y++;
    System.out.println(str.charAt(y-1));
}
查看更多
forever°为你锁心
5楼-- · 2020-08-04 11:01

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).

查看更多
对你真心纯属浪费
6楼-- · 2020-08-04 11:03

Try this:

String s = String.valueOf(x);
int index = s.length()- y;
char result = s.charAt(index);
查看更多
登录 后发表回答