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);
CodePudding user response:
You can actually skip all the loops here and use strings
.
Like this:
public static int swapNr(int nr)
{
String nrStr = String.valueOf(nr); // Turning our nr into a String
char[] charArr = nrStr.toCharArray(); // Getting the char Array out of it
char firstNr = charArr[0]; // Getting the first character
char lastNr = charArr[charArr.length - 1]; // Getting the last one
// Changing their places
charArr[0] = lastNr;
charArr[charArr.length - 1] = firstNr;
return Integer.parseInt(String.valueOf(charArr)); // Turning the String into an Integer again
}
String.replace()
would not be the correct way to change the place of a specific character in a String
. And you must know that Strings
are immutable, that means that when you call .replace()
, the function returns a new String
and does not update the current one.
CodePudding user response:
You can do this completely without loops, using only arithmetic:
public static int swap(int v) {
final int lastDigit = v % 10;
// the number of digits - 1 (1 digit = 0, 2 digits = 1, ...)
final int digitsMinusOne = (int) Math.floor(Math.log10(v));
// the multiplier used for getting/setting the first digit
// examples:
// 1234, digitsMinusOne=3, multiplier = 10^3 = 1000
// 827382, digitsMinusOne=5, multiplier = 10^5 = 100000
final int multiplier = (int) Math.pow(10, digitsMinusOne);
// the first digit can be retrieved by dividing by the multiplier
// for example:
// 1234 / 1000 = 1
// 827382 / 100000 = 8
final int firstDigit = v / multiplier;
// replacing the last digit with the first digit
v = (v - (v % 10)) firstDigit;
// replacing the first digit with the last digit
v = (v - (firstDigit * multiplier)) (lastDigit * multiplier);
return v;
}
CodePudding user response:
It's easier not to use for-loops.
static int swapFirstAndLastDigit(int n) {
return Integer.parseInt(("" n)
.replaceFirst("^(-)?(.)(.*)(.)$", "$1$4$3$2"));
}
public static void main(String[] args) {
System.out.println(swapFirstAndLastDigit(12345));
System.out.println(swapFirstAndLastDigit(-54321));
}
output:
52341
-14325