Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gets last digit of a number

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?
like image 473
catch23 Avatar asked Jun 17 '13 10:06

catch23


People also ask

How do you print the last digit?

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


1 Answers

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

like image 117
Bathsheba Avatar answered Sep 19 '22 23:09

Bathsheba