Gets last digit of a number
Solution 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);
Solution 2:
Below is a simpler solution how to get the last digit from an int
:
public int lastDigit(int number) { return Math.abs(number) % 10; }
Solution 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);
Solution 4:
No need to use any strings
.Its over burden.
int i = 124;
int last= i%10;
System.out.println(last); //prints 4