Compare two numbers without if

Source: Internet
Author: User

I. Problems

There are two variables, a and B, which do not need to be "if", "? : ", Switch or other judgment statements, find the two numbers that are relatively large

Ii. Solutions

/* Method 1: calculate the average value (a + B) + abs (a-B )) /2 is (a + B-abs (a-B)/2 */int fMax1 (int a, int B) {return (a + B) + abs (a-B)/2 ;}
/* Method 2: When abs () a is not used <B, a/B = 0, so the front is B * (B/a), followed by B/, if the result is ba = B, a/B = 1, so the first is a + B = 2a, followed by 2, then the result is aa> B, b/a = 0, so the first is a * (a/B), followed by a/B, then the result is a */int fMax2 (int a, int B) {int larger = (a * (a/B) + B * (B/a)/(a/B + B/); // long smaller = (B * (a/B) + a * (B/a)/(a/B + B/a); return larger ;}
/* Method 3: if the remainder of a/B is not 0, it means that a> B is a good method, but the question says, "? : "*/Int fMax3 (int a, int B) {return (a/B )? A: B ;}
/* Method 4: shift method. If B is less than 0, it is saved as a complement, so the highest bit is 1, so the right shift 31 bits B> 31 is actually the highest bit value B> = 0, the highest bit is 0, so B and 1 are B, a = a-(a-B) = bb and 1 are 0, equivalent to a = a-0 = a */int fMax4 (int a, int B) {B = a-B; a-= B & (B> 31); return a ;}// shift method int fMax5 (int a, int B) {int c [2] = {a, B}; int z = a-B; z = (z> 31) & 1; return c [z];} // shift method int fMax6 (int a, int B) {int flag = (a-B)> 31) & 1; return a-(a-B) * flag ;}
// I think this should be the best of B's int fMax7 (int a, int B) {int pair [2] = {a, B }; return pair [a <B];}

Iii. Feelings

The algorithm is so amazing that you need to think more in the future ···

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.