Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ Macro for finding maximum of two numbers without using ternary operator

I came across a interview question which reads as follows:

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

I need your help in solving this. I know this is trivial but I couldn't find it. So, posting 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);
}
like image 411
Ani Avatar asked Sep 19 '14 04:09

Ani


6 Answers

Use Boolean operations to get 0 or 1 and then just add them up:

#define max(x,y) (((int)((x)<(y)) * (y)) + ((int)((y)<=(x)) * (x)))
like image 120
Rich Avatar answered Oct 14 '22 21:10

Rich


#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);
};

a solution just for fun : > compiled with c++14

would blow up if x, y has different types

like image 30
owensss Avatar answered Oct 14 '22 23:10

owensss


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

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

As pointed out in the comments, using abs might violate the conditions what you have asked for.

like image 37
Pradhan Avatar answered Oct 14 '22 22:10

Pradhan


#define max(x, y) x - ((x-y) & ((x-y) >> 31))

This assumes x and y are 32 bit.

This works by the fact that the most-significant bit of a negative integer is 1.

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

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

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

I imagine this is what they're looking for since it doesn't use comparisons.

like image 31
paiego Avatar answered Oct 14 '22 22:10

paiego


Aww, so many nice solutions. I have another one exploiting that booleans convert to zero and one:

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

Nearby, I'm deliberately ALL_UPPERCASING this evil macro machinery. I'd say this is the actual point you should have raised in an interview.

like image 30
Ulrich Eckhardt Avatar answered Oct 14 '22 22:10

Ulrich Eckhardt


Another crazy C++11-only approach, and cheating slightly with an extra struct declaration (could use a std::array if libraries were allowed) - for whatever it's worth (not much!)...

struct Max { int n_[2]; };
#define max(x,y) (Max{(x),(y)}.n_[(x) < (y)])
like image 43
Tony Delroy Avatar answered Oct 14 '22 21:10

Tony Delroy