Gets last digit of a number

早过忘川 提交于 2019-11-26 11:20:44

问题


I need to define the last digit of a number assign this to value. After this, return the last digit.

My snippet of code doesn\'t work correctly...

Code:

public int lastDigit(int number) {
    String temp = Integer.toString(number);
    int[] guess = new int[temp.length()];
    int last = guess[temp.length() - 1];

    return last;
}

Question:

  • How to solve this issue?

回答1:


Just return (number % 10); i.e. take the modulus. This will be much faster than parsing in and out of a string.

If number can be negative then use (Math.abs(number) % 10);




回答2:


Below is a simpler solution how to get the last digit from an int:

public int lastDigit(int number) { return number % 10; }



回答3:


Use

int lastDigit = number % 10. 

Read about Modulo operator: http://en.wikipedia.org/wiki/Modulo_operation

Or, if you want to go with your String solution

String charAtLastPosition = temp.charAt(temp.length()-1);



回答4:


No need to use any strings.Its over burden.

int i = 124;
int last= i%10;
System.out.println(last);   //prints 4



回答5:


Without using '%'.

public int lastDigit(int no){
    int n1 = no / 10;
    n1 = no - n1 * 10;
    return n1;
}



回答6:


You have just created an empty integer array. The array guess does not contain anything to my knowledge. The rest you should work out to get better.




回答7:


Your array don't have initialization. So it will give default value Zero. You can try like this also

String temp = Integer.toString(urNumber);
System.out.println(temp.charAt(temp.length()-1));



回答8:


Use StringUtils, in case you need string result:

String last = StringUtils.right(number.toString(), 1);



回答9:


Another interesting way to do it which would also allow more than just the last number to be taken would be:

int number = 124454;
int overflow = (int)Math.floor(number/(1*10^n))*10^n;

int firstDigits = number - overflow;
//Where n is the number of numbers you wish to conserve</code>

In the above example if n was 1 then the program would return: 4

If n was 3 then the program would return 454




回答10:


public static void main(String[] args) {

    System.out.println(lastDigit(2347));
}

public static int lastDigit(int number)
{
    //your code goes here. 
    int last = number % 10;

    return last;
}

0/p:

7




回答11:


here is your method

public int lastDigit(int number)
{
    //your code goes here. 
    int last =number%10;
    return last;
}



回答12:


Although the best way to do this is to use % if you insist on using strings this will work

public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}

but I just wrote this for completeness. Do not use this code. it is just awful.



来源:https://stackoverflow.com/questions/17144997/gets-last-digit-of-a-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!