Issue
This is my code (which is not working) without using loops.
System.out.println("Enter a five digit number: ");
int number = scanner.nextInt();
int lastDigit = number % 10; //by using the % operator, we are able to retrieve the last digit of the number
int firstDigit = number;
while(firstDigit > 9) {
firstDigit /= 10;
}
//======================================================//
System.out.println("The first digit of the number is " + firstDigit);
System.out.println("The last digit of the number is " + lastDigit);
String string = Integer.toString(number);
char first = string.charAt(0);
char last = string.charAt(string.length() - 1);
string.replace(first, last);
string.replace(last, first);
System.out.println(string);
Solution
A method to swap the digits using for
loop:
static int swapDigits(int x) {
System.out.print(x + " -> ");
int sign = Integer.signum(x);
x *= sign; // invert negative number if necessary
int last = x % 10;
int n = x / 10;
int s = 0; // sum for the digits in the middle
for (int p = 1; n > 10; n /= 10, last *= 10, p *= 10) {
s += p * (n % 10);
}
return sign * (10 * (last + s) + n); // restore the sign and get swapped digits
}
Tests:
System.out.println(swapDigits(12345)); // 12345 -> 52341
System.out.println(swapDigits(607081)); // 607081 -> 107086
System.out.println(swapDigits(98760)); // 98760 -> 8769 // leading 0 lost
System.out.println(swapDigits(-12345)); // -12345 -> -52341
Answered By - Nowhere Man
Answer Checked By - Gilberto Lyons (JavaFixing Admin)