Detect if two integers have opposite signs

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 for -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.

#include<stdio.h>
 
booloppositeSigns(intx, inty)
{
    return((x ^ y) < 0);
}
 
intmain()
{
    intx = 100, y = -100;
    if(oppositeSigns(x, y) == true)
       printf("Signs are opposite");
    else
      printf("Signs are not opposite");
    return0;
}


Output:

Signs are opposite

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

booloppositeSigns(intx, inty)
{
    return(x < 0)? (y >= 0): (y < 0);
}


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.

booloppositeSigns(intx, inty)
{
 return((x ^ y) >> 31);
}


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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值