← All problems · Bit Manipulation
Check Whether Two Integers Have Opposite Signs
Return 1 when exactly one of x and y is negative. Treat zero as nonnegative. Use bitwise operations.
Implement int opposite_signs(int32_t x, int32_t y).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
XOR the sign bits.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
int opposite_signs(int32_t x, int32_t y)
{
return (((uint32_t)x ^ (uint32_t)y) >> 31)!=0;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
int opposite_signs(std::int32_t x, std::int32_t y)
{
return (((std::uint32_t)x ^ (std::uint32_t)y) >> 31)!=0;
}
XOR sets the top bit when the signs differ. Unsigned conversion and shifting avoid signed shift issues.
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(opposite_signs(-1,1)==1);
CHECK(opposite_signs(1,2)==0);
CHECK(opposite_signs(-1,-2)==0);
CHECK(opposite_signs(0,-1)==1);
CHECK(opposite_signs(INT32_MIN,INT32_MAX)==1);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}