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:
Just return (number % 10); i.e. take the modulus. This will be much faster than parsing in and out of a string.
(number % 10)
If number can be negative then use (Math.abs(number) % 10);
number
(Math.abs(number) % 10);
2.1m questions
2.1m answers
60 comments
57.0k users