Interview Questions: Maximum, minimum, and variable exchange of two variables

Source: Internet
Author: User

// XK> example

[Question] If ,? :, Switch, and other judgment statements to find the maximum and minimum values of the two given Variables

[Answer] A + B may cause overflow.

The answer below is from 《ProgramThe second edition of the "Employee Interview Guide" obviously has overflow problems. However, this idea is a bit interesting.

Int max = (a + B + ABS (a-B)> 1; int min = (a + B-ABS (a-B)> 1;

This question is purely an odd sex technique and does not make much sense. The Solution Below is better, but a-B may also overflow during the negative number operation!

Int max = A-(a-B)> 31) & (a-B); int min = a + (B-a)> 31) & (B-));

// XK> example

Question: exchange the values stored in two instead of 3rd variables.

[Answer] This is a common tip in programming. The answer below is a good note. The Three ^ = operators are alternately filled with two variable names.

A ^ = B ^ = a ^ = B;

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.