Gets last digit of a number

catch23 picture catch23 · Jun 17, 2013 · Viewed 128.4k times · Source

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?

Answer

Bathsheba picture Bathsheba · Jun 17, 2013

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