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

后端 未结 10 999
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
    
    0 讨论(0)
  • 2020-12-13 01:00

    C++11 allows to:

    • Swap values:

      std::swap(a, b);
      
    • Swap ranges:

      std::swap_ranges(a.begin(), a.end(), b.begin());
      
    • Create LValue tuple with tie:

      std::tie(b, a) = std::make_tuple(a, b);
      
      std::tie(c, b, a) = std::make_tuple(a, b, c);
      
    0 讨论(0)
  • 2020-12-13 01:06
    a=a+b;
    b=a-b;
    a=a-b;
    

    This is simple yet effective....

    0 讨论(0)
  • 2020-12-13 01:06

    In C this should work:

    a = a^b;
    b = a^b;
    a = a^b;
    

    OR a cooler/geekier looking:

    a^=b;
    b^=a;
    a^=b;
    

    For more details look into this. XOR is a very powerful operation that has many interesting usages cropping up here and there.

    0 讨论(0)
提交回复
热议问题