How do I swap the places of an int in java?
algorithm, java
Solution
Here's the solution (tested):
public static int swapDigitPairs(int number) {
int result = 0;
int place = 1;
while (number > 9) {
result += place * 10 * (number % 10);
number /= 10;
result += place * (number % 10);
number /= 10;
place *= 100;
}
return result + place * number;
}
The key points here are:
- the loop consumes digits from the right hand side of the number, so the odd/even processing distinction is gracefully handled
- the terminating condition is that there are at least two digits remaining
- loop logic deals with two digits per iteration
- use the remainder operator `%` with 10 (ie `number % 10`) to produce the last digit
- integer division by 10 numerically truncates the last digit
- there is no need to hold the last digit in a variable - it just clutters the code
Here's some tests and some edge cases:
public static void main(String[] args) throws Exception {
System.out.println(swapDigitPairs(482596));
System.out.println(swapDigitPairs(1234567));
System.out.println(swapDigitPairs(12));
System.out.println(swapDigitPairs(1));
System.out.println(swapDigitPairs(0));
}
Output:
845269
1325476
21
1
0
Problem
I need to swap places of an int. For example, if I call for the method swapDigitPairs(482596), it will return me 845269. The 9 and 6 are swapped, as are the 2 and 5, and the 4 and 8. If the number contains an odd number of digits, leave the leftmost digit in its original place. For example, the call of swapDigitPairs(1234567) would return 1325476. I'm not suppose to solve using a string and I should use a while loop to solve it. I'm not supposed to use any arrays. Below is what I have done so far. But I am stuck at the swapping position and I know I need to multiply by the places(like tenth,thousand etc) depending on the number.But I am stuck at this part. What I have done is to retrieve the number one by one. ``` public static int swapDigitPairs(int number) { while(number!=0) { int firstDigit = number%10; for(int i =10;i<=;i*=10) { int secondDigit= firstDigit*i; } int leftOverDigit = number/10; number=leftOverDigit; } return number; } ```