+ 1
Can anyone help me with a C++ program to swap values of three variables using bitwise operator??
4 ответов
+ 10
Here you go:
x=x^y^z;
y=x^y^z;
z=x^y^z;
x=x^y^z;
+ 9
And here's the code example:
#include <iostream>
using namespace std;
void swap(int x, int y, int z) {
x=x^y^z;
y=x^y^z;
z=x^y^z;
x=x^y^z;
cout<<x<<endl<<y<<endl<<z;
}
int main() {
int x=1, y=2, z=3;
swap(x, y, z);
return 0;
}
+ 7
You can use XOR (exclusive or).
example code:
x = x XOR y XOR z;
y = x XOR y XOR z;
z = x XOR y XOR z;
x = x XOR y XOR z;
+ 6
Swapping values are easy, but I'm not familiar with using bitwise operators. May need someone better to come across this thread.