Write a method named swapDigitPairs that accepts an integer n as a parameter and
ID: 3688364 • Letter: W
Question
Write a method named swapDigitPairs that accepts an integer n as a parameter and returns a new integer whose value is similar to n's but with each pair of digits swapped in order. For example, the call of swapDigitPairs(482596) would return 845269. Notice that 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. You should solve this problem without using a String.
Explanation / Answer
import java.io.*;
class SwapDigits
{
public static void main (String args[])
{
int s;
s = swapDigitPairs(482596);
public int swapDigitPairs(int n)
{
int forSwap, result = 0, counter = 0;
while ((forSwap = n % 100) >= 10)
{
n /= 100;
int a = forSwap / 10, b = forSwap % 10;
result += (b*10+a)*Math.pow(100, counter++);
}
return result + n * (int)Math.pow(100, counter);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.