Summary of the exchange method of two variables

Several swap methods other than introducing third-party variables. .


Implemented using the XOR operation


#include<iostream>
using namespace std;

int main()
{
    int a = 4;
    int b = 5;
    cout << "a= " << a << endl;
    cout << "b= " << b <<endl;
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    cout << "改变后:\n";
    cout << "a= " << a << endl;
    cout << "b= " << b <<endl;
    return 0;
}

Swap using bit operations

#include<iostream>
using namespace std;

int main()
{
    int a = 4;
    int b = 5;
    cout << "a= " << a << endl;
    cout << "b= " << b << endl;
    cout << "改变后:\n";
    b = (int64_t)((int64_t)a << 32 | (a = b)) >> 32;
    cout << "a= " << a << endl;
    cout << "b= " << b << endl;
}

The value of a was originally 32 bits, and after forcibly converted to 64 bits, the value of a was shifted to the left by 32 bits, and then the value of b was assigned to the original memory of a, and then the OR operation was performed. After the operation, in the 64-bit, the low-order bit is the original value of b. At this time, the entire result is shifted to the right by 32 bits, and then forcedly converted to int64_t type and assigned to b. At this point, output a and b to complete the exchange. The coercion type conversion is equivalent to providing an extra space to exchange two variables, and the coercion conversion is to expand a space on the original basis.

Implementation using stack

Use first-in, last-out thinking


#include<iostream>
using namespace std;

int main()
{
    int a,b;
    push(stack,a);
    push(stack,b);
    pop(stack,&b);
    pop(stack,&a);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326362280&siteId=291194637