"Sword means offer" does not use the new variable, exchange the value of two variables, C + + implementation

Source: Internet
Author: User

# topics

Swaps the values of two variables without using a new variable.

# ideas

method One: use the Add and subtract operation to exchange the values of two variables.

A = A+b

B = a A

A = A-B

method Two: exchange values of two variables using XOR operation

A = A^b

B = A^b

A = A^b

# code

#include <iostream>using namespace std;void fun1 (int m,int n) {cout<<"method One, exchange two variables based on addition and subtraction"<<Endl; M= m +N; N= M-N; M= M-N; cout<<m<<"    "<<n<<Endl;} void fun2 (int m,int n) {cout<<"method Two, exchange two variables based on XOR operation"<<Endl; M= m^N; N= m^N; M= m^N; cout<<m<<"    "<<n<<Endl;} int main () {int M= 10; int n= 20; cout<<"Original Value"<<Endl; cout<<m<<"    "<<n<<Endl;    FUN1 (M,n);    Fun2 (M,n); return0;}

"Sword means offer" does not use the new variable, exchange the value of two variables, C + + implementation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.