Switch numbers in int array according to a pattern

Viewed 295

I've been scanning the internet trying to come up with a solution for this simple program that will basically take user input in numbers (a telephone number) and change every number according to the following rules:

0 → (becomes) 5, 1 → 9, 2 → 8, 3 → 7, 4 → 6, 5 → 0, 6 → 4, 7 → 3, 8 → 2, 9 → 1.

So a number of 7784321600 becomes 3326789455.

I took user input as a String, converted it to an int array but when I try to swap, I don't get it to work as well as I hoped for.

I tried to swap the values with the in the following way:

for (int i = 0; i < input.length(); i++) {
    if (nrArray[i] == 0) {
        // 0 becomes 5
        int temp0[] = { 5 };
        nrArray[i] = nrArray[i] + temp0[i];
        temp0[i] = nrArray[i] - temp0[i];
        nrArray[i] = nrArray[i] - temp0[i];
    }
}

which works OK if it was only going to swap numbers 0-4, as soon as it reaches 5-9, the code will reverse it again like this:

for (int i = 0; i < input.length(); i++) {
    if (nrArray[i] == 5) {
        // 5 becomes 0
        int temp0[] = { 0 };
        nrArray[i] = nrArray[i] + temp0[i];
        temp0[i] = nrArray[i] - temp0[i];
        nrArray[i] = nrArray[i] - temp0[i];
    }
}

I also tried thereplaceAll method for changing the string, but the same problem occurs.

Any suggestions?

11 Answers
Related