Exchange two variables without referencing the third variable.

Source: Internet
Author: User
Document directory
  • Exchange two variables without referencing the third variable.
Exchange two variables without referencing the third variable. A few days ago, I went to the interview and was asked this question. At that time, I couldn't answer it, and he didn't care. the second company was still asked this question, but still did not answer it. come back and ask me, I don't know how to solve it. I think there must be a good solution, but I just can't think of it. there were still many students who did not know about the party in Suzhou last night. After being explained by the singer, they could find a good solution.

As follows:
Void swap (int a, int B)

{

A = a ^ B;

B = B ^ a; // B ^ a is equal to B ^ a ^ B, that is, the value of B ^ a ^ B is a, and the following is the same

A = a ^ B;

}

In fact, it is very simple, just don't think of it. If you want to go to the interview, can it be useful?

The above method should be swap (ref int a, ref int B). To keep the original color, do not change it. This sentence is added on the 29th.

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.