Check whether two integers have opposite signs with a single bitwise expression.
Solution
main.c
#include <stdbool.h>
#include <stdio.h>
bool opposite_signs(int a, int b) {
return (a ^ b) < 0; /* sign bit of the XOR is 1 only if the sign bits differ */
}
int main(void) {
int pairs[][2] = {{5, -3}, {-4, -9}, {7, 0}};
for (int i = 0; i < 3; i++)
printf("%d, %d: %s\n", pairs[i][0], pairs[i][1],
opposite_signs(pairs[i][0], pairs[i][1]) ? "opposite" : "same");
return 0;
}
Output Verified by compiling and running
5, -3: opposite
-4, -9: same
7, 0: same
The sign bit of a ^ b is 1 exactly when one number is negative and the other is not. Unlike a * b < 0, it cannot overflow. Zero counts as non-negative.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!