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:
digit = num % 10; We find out the last digit of the number by dividing it by 10, this gives us the remainder which is the last digit of the number. printf("Last Digit of %d is: %d", num, digit); // Displaying output printf("Last Digit of %d is: %d", num, digit);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With