java get last digit of int code example

Example 1: find last digit of number

//C++
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));
	// write your code here
    }
    public static int sumFirstAndLastDigit(int number){
        if (number<0){
            return -1;  //checking boundary conditions
        }
        else if(number==0){
            return 0;
        }
        else{
            int lastDigit=number%10; // to extract last significant digit
            while(number>=10){
                number=number/10;
            }
            int firstDigit=number;
            return (lastDigit+firstDigit);
        }
    }

Tags:

Cpp Example