给定两个有符号整数,如果给定整数的符号不同,则编写一个返回true的函数,否则返回false。例如,该函数应返回true -1和+100,并且对于-100和-200应该返回false。该函数不应使用任何算术运算运算符。
令给定的整数为x和y。符号位是1(负数)和0(正数)。如果x和y的符号相反,则它们的XOR将具有1的符号位。换句话说,x和y的XOR将为负数,且x和y的符号相反。以下代码使用此逻辑。
C++
// C++ Program to Detect
// if two integers have opposite signs.
#include
#include
bool oppositeSigns(int x, int y)
{
return ((x ^ y) < 0);
}
int main()
{
int x = 100, y = -100;
if (oppositeSigns(x, y) == true)
printf ("Signs are opposite");
else
printf ("Signs are not opposite");
return 0;
}
Java
// Java Program to Detect
// if two integers have opposite signs.
class GFG {
static boolean oppositeSigns(int x, int y)
{
return ((x ^ y) < 0);
}
public static void main(String[] args)
{
int x = 100, y = -100;
if (oppositeSigns(x, y) == true)
System.out.println("Signs are opposite");
else
System.out.println("Signs are not opposite");
}
}
// This code is contributed by prerna saini.
Python3
# Python3 Program to Detect
# if two integers have
# opposite signs.
def oppositeSigns(x, y):
return ((x ^ y) < 0);
x = 100
y = 1
if (oppositeSigns(x, y) == True):
print "Signs are opposite"
else:
print "Signs are not opposite"
# This article is contributed by Prerna Saini.
C#
// C# Program to Detect
// if two integers have
// opposite signs.
using System;
class GFG {
// Function to detect signs
static bool oppositeSigns(int x, int y)
{
return ((x ^ y) < 0);
}
// Driver Code
public static void Main()
{
int x = 100, y = -100;
if (oppositeSigns(x, y) == true)
Console.Write("Signs are opposite");
else
Console.Write("Signs are not opposite");
}
}
// This code is contributed by Nitin Mittal.
PHP
Javascript
CPP
bool oppositeSigns(int x, int y)
{
return (x < 0)? (y >= 0): (y < 0);
}
CPP
bool oppositeSigns(int x, int y)
{
return ((x ^ y) >> 31);
}
输出:
Signs are opposite
来源:检测两个整数是否具有相反的符号
我们也可以通过使用两个比较运算符解决这个问题。请参阅以下代码。
CPP
bool oppositeSigns(int x, int y)
{
return (x < 0)? (y >= 0): (y < 0);
}
第一种方法更有效。第一种方法使用按位异或并运算符。第二种方法使用两个比较运算符,与比较运算符相比,按位XOR运算效率更高。
我们也可以使用以下方法。它不使用任何运算符。该方法由Hongliang提出,并由gaurav进行了改进。
CPP
bool oppositeSigns(int x, int y)
{
return ((x ^ y) >> 31);
}
该函数仅适用于整数大小为32位的编译器。该表达式基本上使用按位运算运算符’>>’检查(x ^ y)的符号。如上所述,负数的符号位始终为1。符号位是二进制表示形式中最左边的位。因此,我们需要检查x ^ y的第32位(或最左边的位)是否为1。我们通过将x ^ y的值右移31来做到这一点,以使符号位变为最低有效位。如果符号位为1,则(x ^ y)>> 31的值将为1,否则为0。