How to swap digits in java

12.5k Views Asked by At

I am trying to practice java over the summer and i'm stuck on this problem. I need to swap the 2 letters in a integer in java. For example in my main method I make a method called swapdigits and have my parameters as 1432. The program should swap the 4 and 1 and 3 and 2. The output should be 4123 since it swapped the two letters in order. Lets say I do swapdigits(1341234) the output should be 3114324. I know I have to use while loops but i'm getting stuck on the swapping.

This is what I have so far:

public static void main(String[] args) {
    Swapdigits(2413);

}
public static void Swapdigits(int number){

    while(number>0){
        int y=number/1000;
        int x=number%10;
        int original=number-y;
        System.out.println(original);
    }
     System.out.println();
    }

}
2

There are 2 best solutions below

2
On BEST ANSWER
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;
}

You can also try

char[] a = String.valueOf(number).toCharArray();
for (int i = 0; i < a.length - 1; i += 2) {
    char tmp = a[i];
    a[i] = a[i + 1];
    a[i + 1] = tmp;
}
int number = Integer.parseInt(new String(a));
0
On

Because you're just swapping the places of digits, it doesn't actually matter what the number is. So, it's probably easier (and makes more sense) to represent the argument as a string. That way you aren't dealing with weird modulo operators - If you were solving the problem by hand, would you actually do any math? You'd treat this problem the same whether it were numbers of a bunch of characters.

Take a look at the following question for information on swapping characters in a String: How to swap String characters in Java?