How to swap without a third variable?

前端 未结 6 1236
死守一世寂寞
死守一世寂寞 2020-12-29 14:12

I have to swap two variables with a number value without using a third variable. What is the simple solution?

6条回答
  •  死守一世寂寞
    2020-12-29 14:20

    Here we have this in MIPS assembler. The first solution is long and bad. The second one with XOR is better.

    addi $t0, $0, -5
    addi $t1, $0, 15
    
    add $t0, $t0, $t1
    sub $t1, $t1, $t0
    nor $t1, $0, $t1
    addi $t1, $t1, 1
    sub $t0, $t0, $t1
    
    ####
    
    xor $t0, $t0, $t1
    xor $t1, $t0, $t1
    xor $t0, $t0, $t1
    

提交回复
热议问题