swap很常见,这里总结可以实现swap功能的方式:
提倡用第一种办法,异或或加减并没有减少时间,相反,异或会增加运算量,不具有实用性.
#include<iostream> #include<stack> using namespace std; void swap_normal(int& a,int& b) { int temp=a; a=b; b=temp; } void swap_stack(int& a,int& b) { stack<int> st; st.push(a); st.push(b); a=st.top(); st.pop(); b=st.top(); st.pop(); } void swap_add(int& a,int& b) { a=a+b; b=a-b; a=a-b; } void swap_mul(int& a,int& b) { a=a*b; b=a/b; a=a/b; } void swap_xor(int& a,int& b) { if(a != b) { a^=b; b^=a; a^=b; } } int main() { int a,b; while(1) { cin>>a>>b; swap_stack(a,b); cout<<a<<" "<<b<<endl; } return 0; }