SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:18 | ISBN:9780136091813 | Edition: 2

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package indefinite_loops;

public class SwapDigitPairs {

    public int swapDigitPairs(int number) {
        int result = 0;
        int m = 1;
        
        // as long as number is greater than zero
        while( number > 0) {
            int d1 = number % 10;
           number /= 10;
            
           // if num = 0 break the loop
            if( number == 0) {
                result += m * d1; 
                break;
            }
            
            // otherwise the divide the number with 10 continously
            int d2 = number % 10;
            result = result + m * 10 * d1 + m * d2;
           number /= 10;
            m *= 100;
        }
        
        // return the result
        return result;
    }

    
    // driver method
    public static void main(String[] args) {
        
        // create object and call the method
        SwapDigitPairs sw = new SwapDigitPairs();
        System.out.println("swapped pairs of digits is: " +sw.swapDigitPairs(248657));
        

    }

}

 

0 0

Discussions

Post the discussion to improve the above solution.