Created
August 18, 2014 13:44
-
-
Save ivycheung1208/20eda9723c9b44eac1e4 to your computer and use it in GitHub Desktop.
CC150 17.4
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
/* CC150 17.4 */ | |
// find the maximum of two numbers without if-else or any comparison operator | |
#include <iostream> | |
int sign(int n) { return (n >> 31) & 0x1 ^ 1; } // 1 for positive and 0 for negative | |
int maxNumber(int a, int b) | |
{ | |
// if ab < 0, return the positive one, filt = sign(a) | |
// if ab > 0, filt = sign(a - b) (which would not overflow since a, b have the same sign) | |
int difSign = sign(a) ^ sign(b); | |
int filt = difSign * sign(a) + (1 - difSign) * sign(a - b); | |
return filt * a + (1 - filt) * b; | |
} | |
int main() | |
{ | |
int a, b; | |
std::cin >> a >> b; | |
std::cout << maxNumber(a, b) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment