Given two signed integers, write a function that returns true if the signs of given integers are different, otherwise false. For example, the function should return true -1 and +100, and should return false for -100 and -200. The function should not use any of the arithmetic operators.

Let the given integers be x and y. The sign bit is 1 in negative numbers, and 0 in positive numbers. The XOR of x and y will have the sign bit as 1 iff they have opposite sign. In other words, XOR of x and y will be negative number number iff x and y have opposite signs. The following code use this logic.

 

 

[pastacode lang=”c” manual=”%23include%3Cstdbool.h%3E%0A%23include%3Cstdio.h%3E%0A%20%0Abool%20oppositeSigns(int%20x%2C%20int%20y)%0A%7B%0A%20%20%20%20return%20((x%20%5E%20y)%20%3C%200)%3B%0A%7D%0A%20%0Aint%20main()%0A%7B%0A%20%20%20%20int%20x%20%3D%20100%2C%20y%20%3D%20-100%3B%0A%20%20%20%20if%20(oppositeSigns(x%2C%20y)%20%3D%3D%20true)%0A%20%20%20%20%20%20%20printf%20(%22Signs%20are%20opposite%22)%3B%0A%20%20%20%20else%0A%20%20%20%20%20%20printf%20(%22Signs%20are%20not%20opposite%22)%3B%0A%20%20%20%20return%200%3B%0A%7D” message=”c” highlight=”” provider=”manual”/]

Output:

Signs are opposite

Source: Detect if two integers have opposite signs

[ad type=”banner”]

We can also solve this by using two comparison operators. See the following code.

[pastacode lang=”c” manual=”bool%20oppositeSigns(int%20x%2C%20int%20y)%0A%7B%0A%20%20%20%20return%20(x%20%3C%200)%3F%20(y%20%3E%3D%200)%3A%20(y%20%3C%200)%3B%0A%7D” message=”c” highlight=”” provider=”manual”/]

The first method is more efficient. The first method uses a bitwise XOR and a comparison operator. The second method uses two comparison operators and a bitwise XOR operation is more efficient compared to a comparison operation.

[ad type=”banner”]

We can also use following method. It doesn’t use any comparison operator. The method is suggested by Hongliang and improved by gaurav.

[pastacode lang=”c” manual=”bool%20oppositeSigns(int%20x%2C%20int%20y)%0A%7B%0A%20%20%20%20return%20((x%20%5E%20y)%20%3E%3E%2031)%3B%0A%7D” message=”c” highlight=”” provider=”manual”/]

The function is written only for compilers where size of an integer is 32 bit. The expression basically checks sign of (x^y) using bitwise operator ‘>>’. As mentioned above, the sign bit for negative numbers is always 1. The sign bit is the leftmost bit in binary representation. So we need to checks whether the 32th bit (or leftmost bit) of x^y is 1 or not. We do it by right shifting the value of x^y by 31, so that the sign bit becomes the least significant bit. If sign bit is 1, then the value of (x^y)>>31 will be 1, otherwise 0.

[ad type=”banner”]