C / C ++ Macro to find a maximum of two numbers without using the triple operator

I came across an interview question that reads:

"Write a simple C / C ++ macro to find a maximum of two numbers without using the std library or the triple operator."

I need your help in resolving this. I know this is trivial, but I could not find it. So post it here.

#include<iostream> #define max(x,y) /*LOGIC HERE*/ using namespace std; void main() { int a = 98453; int b = 66394; cout<<max(a,b); } 
+5
source share
6 answers

Use logical operations to get 0 or 1, and then just add them:

 #define max(x,y) (((int)((x)<(y)) * (y)) + ((int)((y)<=(x)) * (x))) 
+26
source
 #include <iostream> #define max(x, y) [a = x, b = y](){ if (a<b) return b; else return a; }() int main() { using namespace std; int a = 10; int b = 20; cout << max(10, 20); cout << max(a, b); }; 

the solution is just for fun:> compiled with C ++ 14

explode if x, y has different types

+5
source

#define max(x,y) (x+y + abs(xy))/2 gives you what you are looking for. This works because abs(xy) = max(x,y) - min(x,y) . So you can rewrite the expression as follows

 (x + y) + abs(xy) = max(x,y) + min(x,y) + max(x,y) - min(x,y) = 2*max(x,y) 

As stated in the comments, using abs may violate the conditions you requested.

+3
source
 #define max(x, y) x - ((xy) & ((xy) >> 31)) 

This assumes x and y are 32 bits.

This works because the most significant bit of a negative integer is 1.

Thus, if xy is negative (y is greater than x), then x - (x - y) = y.

If xy is positive, then x is greater than y, the most significant bit is zero, and therefore x - 0 = x.

31 represents the total number of bits of the variable - 1. (thus, the most significant bit).

I guess this is what they are looking for since it does not use comparisons.

+2
source

That's all, so many good decisions. I have one more that uses booleans to convert to zero and one thing:

 #define CONDITION(c, t, f) (c * t + (1 - c) * f) #define MAX(a, b) CONDITION(a > b, a, b) 

Nearby, I intentionally ALL_UPPERCASING this evil macro. I would say that this is the actual moment that you should have touched upon in the interview.

+2
source

Another crazy approach based on C ++ 11 and a small change with the addition of a struct declaration (you can use std::array if libraries are enabled) - for everything that costs (not so much!) ...

 struct Max { int n_[2]; }; #define max(x,y) (Max{(x),(y)}.n_[(x) < (y)]) 
+1
source

Source: https://habr.com/ru/post/1202933/


All Articles