Java – switches the number in the int array according to the mode

I've been scanning the Internet and trying to come up with a solution for this simple program. Basically, users enter numbers (phone numbers) and change each number according to the following rules:

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

Therefore, the number of 7784321600 becomes 3326789455

I convert user input as a string to an int array, but when I try to swap, I can't make it work as I want

I tried to exchange values 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];
    }
}

If it just exchanges numbers 0-4, it can work normally. Once it reaches 5-9, the code will reverse it again, as shown below:

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 the whereplaceall method to change the string, but the same problem occurred

Any suggestions?

Solution

Use hash mapping to store source integers as keys and destination integers as values

int a[] = {7,7,8,2,1,6,0};
Map<Integer,Integer> map = new HashMap<Integer,Integer>();

//0->5,1->9,2->8,3->7,4->6,5->0,6->4,7->3,8->2,9->1
map.put(0,5);
map.put(1,9);
map.put(2,8);
map.put(3,7);
map.put(4,6);
map.put(5,0);
map.put(6,4);
map.put(7,3);
map.put(8,2);
map.put(9,1);

for (int i = 0; i < a.length; i++) {
    a[i] = map.get(a[i]);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>