Skip to content

Instantly share code, notes, and snippets.

@ivycheung1208
Created August 18, 2014 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivycheung1208/20eda9723c9b44eac1e4 to your computer and use it in GitHub Desktop.
Save ivycheung1208/20eda9723c9b44eac1e4 to your computer and use it in GitHub Desktop.
CC150 17.4
/* 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