Detect if two integers have opposite signs

05 Jul, 2022
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 iff x and y have opposite signs. The following code use this logic.  
C++
C
Java
Python3
C#
PHP
Javascript
// C++ Program to Detect// if two integers have opposite signs.#include<iostream>using namespace std; bool oppositeSigns(int x, int y){    return ((x ^ y) < 0);} int main(){    int x = 100, y = -100;    if (oppositeSigns(x, y) == true)    cout << "Signs are opposite";    else    cout << "Signs are not opposite";    return 0;} // this code is contributed by shivanisinghss2110
// C++ Program to Detect // if two integers have opposite signs.#include<stdbool.h>#include<stdio.h>   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 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 Program to Detect # if two integers have # opposite signs.def oppositeSigns(x, y):    return ((x ^ y) < 0);   x = 100y = 1   if (oppositeSigns(x, y) == True):    print ("Signs are opposite")else:    print ("Signs are not opposite")   # This article is contributed by Prerna Saini.
// 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// PHP Program to Detect if two// integers have opposite signs. function oppositeSigns($x, $y){    return (($x ^ $y) < 0);}     // Driver Code    $x = 100;    $y = -100;    if (oppositeSigns($x, $y) == true)    echo ("Signs are opposite");    else    echo ("Signs are not opposite");     // This code is contributed by vt_m.?>
<script> // Javascript Program to Detect // if two integers have opposite signs. function oppositeSigns(x, y)    {        return ((x ^ y) < 0);    } // Driver Code     let x = 100, y = -100;    if (oppositeSigns(x, y) == true)         document.write("Signs are opposite");    else         document.write("Signs are not opposite"); </script>
Signs are opposite
Time Complexity: O(1)
Auxiliary Space: O(1)
Source: Detect if two integers have opposite signsWe can also solve this by using two comparison operators. See the following code.  
CPP
C
Java
Python3
C#
Javascript
bool oppositeSigns(int x, int y){    return (x < 0)? (y >= 0): (y < 0);}
//C program to detect whether two integers//have different sign or not #include <stdio.h>#include<stdbool.h> bool oppositeSigns(int x, int y){    return (x < 0)? (y >= 0): (y < 0);} //this code is contributed by shruti456rawal
class GFG{static boolean oppositeSigns(int x, int y){    return (x < 0)? (y >= 0): (y < 0);}} // This code contributed by umadevi9616
def oppositeSigns(x, y):     return (y >= 0) if (x < 0) else (y < 0); # This code is contributed by shivanisingjss2110
using System;class GFG{static boo oppositeSigns(int x, int y){    return (x < 0)? (y >= 0): (y < 0);}} // This code contributed by shivanisinghss2110
<script>function oppositeSigns(x, y){    return (x < 0)? (y >= 0): (y < 0);}  // This code contributed by shivanisinghss2110</script>
Time Complexity: O(1)
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. We can also use following method. It doesn’t use any comparison operator. The method is suggested by Hongliang and improved by gaurav.  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
CPP
C
Java
Python3
C#
Javascript
bool oppositeSigns(int x, int y){    return ((x ^ y) >> 31);}
//C program to detect whether two integers//have different sign or not #include <stdio.h>#include<stdbool.h> bool oppositeSigns(int x, int y){    return ((x ^ y) >> 31);} //this code is contributed by shruti456rawal
import java.io.*; class GFG {static boolean oppositeSigns(int x, int y){    return ((x ^ y) >> 31);}      } // This code is contributed by shivanisinghss2110
def oppositeSigns(x, y):     return ((x ^ y) >> 31)   # this code is contributed by shivanisinghss2110
using System; class GFG {static bool oppositeSigns(int x, int y){    return ((x ^ y) >> 31);}      } // This code is contributed by shivanisinghss2110
<script>function oppositeSigns(x, y){    return ((x ^ y) >> 31);}   // This code is contributed by shivanisinghss2110</script>
Time Complexity: O(1)
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. 
C++
C
Java
Python3
C#
Javascript
// C++ Program to detect if two integers have opposite// signs.#include <iostream>using namespace std; bool oppositeSigns(int x, int y){    long long product = 1ll * x * y;    return (product < 0);} int main(){    int x = 100, y = -100;    if (oppositeSigns(x, y) == true)        cout << "Signs are opposite";    else        cout << "Signs are not opposite";    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C Program to detect// if two integers have opposite signs.#include <stdbool.h>#include <stdio.h> bool oppositeSigns(int x, int y){    long long product = 1ll * x * y;    return (product < 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;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program for the above approachimport java.util.*; class GFG {   static boolean oppositeSigns(int x, int y)  {    long product = 1*x*y;    return (product<0);  }   // Driver Code  public static void main(String[] args)  {    int x = 100, y = -100;    if (oppositeSigns(x, y) == true)      System.out.print( "Signs are opposite");    else      System.out.print("Signs are not opposite");  }} // This code is contributed by sanjoy_62.
# Python Program to detect# if two integers have opposite signs. def oppositeSigns(x,y):    product = x*y    return (product<0) # driver codex = 100y = -100if(oppositeSigns(x, y) == True):  print("Signs are opposite") else :  print("Signs are not opposite")   # this code is contributed by shinjanpatra
// C# program for the above approachusing System;class GFG{   static bool oppositeSigns(int x, int y)  {    long product = 1*x*y;    return (product<0);  } // Driver Codepublic static void Main(String[] args){    int x = 100, y = -100;    if (oppositeSigns(x, y) == true)      Console.WriteLine( "Signs are opposite");    else      Console.WriteLine("Signs are not opposite");}} // This code is contributed by avijitmondal1998.
// JavaScript Program to detect// if two integers have opposite signs. function oppositeSigns(x,y){    const product = Number(x)*Number(y);    return (product<0);} // driver codelet x = 100, y = -100;if(oppositeSigns(x, y) == true){    console.log("Signs are opposite");}else console.log("Signs are not opposite");   // this code is contributed by shinjanpatra
Signs are opposite
Approach : The basic approach is to calculate the product the two integers, and as we know, two integers having opposite signs will always produce a negative integer, we need to just find out whether the product is negative or not.
Time Complexity: O(1)
Space Complexity: O(1) 
Detect if two integers have opposite signs (Dynamic Programming)  | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersDetect if two integers have opposite signs (Dynamic Programming)  | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=L7OojUR1wFM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. 
nitin mittal
vt_m
code_hunt
kumarmanglam182078
umadevi9616
shivanisinghss2110
subham348
shinjanpatra
sanjoy_62
avijitmondal1998
shruti456rawal
adityakumar129
sagartomar9927
Bitwise-XOR
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bits manipulation (Important tactics)
Divide two integers without using multiplication, division and mod operator
Bit Fields in C
C++ bitset and its application
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Set, Clear and Toggle a given bit of a number in C
Count total set bits in all numbers from 1 to n
Write an Efficient C Program to Reverse Bits of a Number
Position of rightmost set bit
Find two numbers from their sum and XOR