java get last digit of int code example
Example 1: find last digit of number
int last_digit = number % 10;
Example 2: getting the last value of an integer in java
int lastDigit = number % 10
Example 3: find sum of first and last digits in java
public class Main {
public static void main(String[] args) {
System.out.println(sumFirstAndLastDigit(1221));
System.out.println(sumFirstAndLastDigit(2342));
System.out.println(sumFirstAndLastDigit(10));
System.out.println(sumFirstAndLastDigit(-123));
}
public static int sumFirstAndLastDigit(int number){
if (number<0){
return -1;
}
else if(number==0){
return 0;
}
else{
int lastDigit=number%10;
while(number>=10){
number=number/10;
}
int firstDigit=number;
return (lastDigit+firstDigit);
}
}