find sum of first and last digits in java code example
Example: 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);
}
}