-
Notifications
You must be signed in to change notification settings - Fork 691
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added program to find maximum of two without if else
- Loading branch information
1 parent
cddb954
commit 8da5d3f
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |