Bilal Ahmed Khan
Bilal Ahmed Khan

Reputation: 41

Sum of first and last digit

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

Upvotes: 0

Views: 2543

Answers (3)

android developer
android developer

Reputation: 116322

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

Upvotes: 1

knittl
knittl

Reputation: 265131

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

Upvotes: 3

001
001

Reputation: 13533

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;

Upvotes: 2

Related Questions