How to swap two numbers without using temp variables or arithmetic operations?

后端 未结 10 1016
Happy的楠姐
Happy的楠姐 2020-12-13 00:09

This equation swaps two numbers without a temporary variable, but uses arithmetic operations:

a = (a+b) - (b=a);

How can I do it without ar

10条回答
  •  醉梦人生
    2020-12-13 00:57

    Multiplication and division can also be used.

     int x = 10, y = 5;
    
     // Code to swap 'x' and 'y'
     x = x * y;  // x now becomes 50
     y = x / y;  // y becomes 10
     x = x / y;  // x becomes 5
    

提交回复
热议问题