0

I have written a code where I want to add the first and last digit. My code covers scenarios of 1 digit and 2 digits and 3 digits, but not 4 digits. Also, I don't think my code is very simple and efficient, I want to use a while loop to cover all scenarios. Can anyone help, please?

public static void main(String[] args) {
    System.out.println(sumFirstAndLastDigit(10));
}

public static int sumFirstAndLastDigit(int number) {
    int mod = 0;
    int firstdivide = 0;
    int seconddivide = 0;
    int sum = 0;

    if (number < 0) {
        return -1;
    } else if (number > 0 && number < 10) {
        return number + number;
    } else if (number >= 10 && number < 100) {
        mod = number % 10;
        firstdivide = number / 10;
        sum = mod + firstdivide;

        return sum;
    }

    while (number > 0) {
        mod = number % 10;
        firstdivide = number / 10;
        seconddivide = firstdivide / 10;
        sum = mod + seconddivide;

        break;
    }

    return sum;
}
0009laH
  • 1,960
  • 13
  • 27

3 Answers3

3

With a little bit of math, you can easily extract the first and last digit of a number. The last (rightmost) digit is simple with modulo, the first (leftmost) digit can be obtained by calculating the base 10 logarithm of the number.

public static int sumFirstAndLastDigit (int number) {
    if (number < 0) {
        return -1;
    }

    int lastDigit = number % 10;
    int digits = (int)Math.log10(number); // number of digits - 1 
    int firstDigit = (int)(number / Math.pow(10, digits));

    return lastDigit + firstDigit;
}
knittl
  • 246,190
  • 53
  • 318
  • 364
2

Your while loop is not correct. It will always break after 1 iteration.

if (number < 0) {
    return -1;
}
// Get ones digit
int mod = number % 10;
// Keep dividing until only 1 digit left
while (number > 9) {
    number /= 10;
}
return mod + number;
001
  • 13,291
  • 5
  • 35
  • 66
1

How about this simple one:

private static int sumOfFirstAndLastDigits(final int input) {
   int number = Math.abs(input);
   final int lastDigit = number % 10;
   while (number > 9)
       number = number / 10;
   return number + lastDigit;
}
android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • Hi, thanks for your feedback. I think it works great for all scenarios except 1 digit numbers. so example if i put 8, then the output will again be 8 where as i want it to be 16 – Bilal Ahmed Khan Sep 29 '20 at 19:00
  • 1
    In that case, either change the first return to `return number+number` (`return 2*number`) or simply remove the first if altogether. "This is left as an exercise to the reader" :) – knittl Sep 29 '20 at 19:04
  • Well I assumed that if it's 1 digit, it's not a sum of 2 numbers anymore. OK fixed. – android developer Sep 29 '20 at 20:58