You do not need to compare operators and loop control statements to determine the size of A and B in int type.

Source: Internet
Author: User

When I saw this question, I first thought of A-B and then determined whether the highest sign bit is 1 or 0 .. I think everyone will think of this:

Int max (int A, int B) {int MAX [2] = {a, B}; return MAX [(a-B) & 0x80000000)> 31]; // operation. set all the 31 digits after the highest bit to 0, and remove the 31 digits from the right to remove the symbol}

In general, the above Code can produce correct results, but when a is the minimum value of the int type and B is the maximum value of the int type, the subtraction will be out of bounds, and the symbol bit is lost. In fact, there is no such extreme example, because the number of two different symbols is easy to cross-border. So on the basis of this Code, I first judge the symbol bits of A and B, and increase the limit (the symbol is the same, it is reduced, so it is safe, no problem; if the symbol is the opposite, if A is a positive number, B is a negative number, and the maximum or minimum value is obtained directly), so the following code is available:

# Include "stdio. H "# include" stdlib. H "int min (int A, int B) // first judge the symbol bit. When the symbol is the same, the two numbers subtract {return (A> 31 = 0) & (B> 31 = 1) | (A> 31) ^ (B> 31) = 0) & (a-B)> 31) = 0 ))? B: A; // printf ("% s \ n", (A> 31 = 0) & (B> 31 = 1 )) | (A> 31) ^ (B> 31) = 0) & (a-B)> 31) = 0 ))? "A> = B": "A <B");} int main (void) {int A = 0x80000000; // int type minimum int B = 0x7fffffff; // maximum value of int type printf ("% d \ n", min (A, B); System ("pause"); Return 0 ;}

 

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.