-1

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();
    }

}
Cooldude
  • 63
  • 1
  • 1
  • 7

2 Answers2

1
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));
guy_sensei
  • 513
  • 1
  • 6
  • 21
  • @Cooldude It should leave the first digit if the number has odd number of digits, I also included a second solution involving an array. – guy_sensei Jun 09 '15 at 18:47
  • 2
    If it doesn't work then please don't accept it. This may confuse some other user searching for the same problem. But you may upvote good answers/efforts. Or if making some modification to a given answer works for you then update the answer accordingly. – Razib Jun 09 '15 at 18:57
1

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?

Community
  • 1
  • 1
jlbrooks
  • 111
  • 5