Skip to content

Commit

Permalink
Added program to find maximum of two without if else
Browse files Browse the repository at this point in the history
  • Loading branch information
anjalijaiswal08 committed Oct 23, 2018
1 parent cddb954 commit 8da5d3f
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Tricky Problems/maxOfTwo.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//Max of two num with overflow condition
//Refrence : Cracking Coding Interview by Gayle Lakmann Mcdowell

#include <bits/stdc++.h>
using namespace std;

//XOR of bit to convert 1 into 0 and 0 into 1
int flip(int m){
return (1 ^ m);
}

//Return 1 if positive, 0 if a is negative.
int sign(int m){
return ((m >> 31) & 0x1);
}

void max(int a,int b){
int c = a - b;
int sa = sign(a);
int sb = sign(b);
int sc = sign(c);

int sign_a = sa ^ sb;

int sign_c = flip(sa ^ sb);

int k = sign_a * sa + sign_c * sc;

int q = flip(k);

int res = a * q + b * k;

cout<<"Max Of "<<a<<" and "<<b<<"is: ";
cout<<res;
}

int main(){
int a,b;
cin>>a>>b;
max(a,b);
return 0;
}

0 comments on commit 8da5d3f

Please sign in to comment.