'How to compare signs of two numbers without using < or >?
I need to compare 2 numbers, if they have the same sign (positive or negative), print "same sign". If they have a different sign, print "different sign"
The catch is, I need to do it without the use of < or > (greater than or less than) and only using addition and subtraction of num1 and num2. You can also use 0 (no other numbers).
Here is what it looks like with the <>s:
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
if num1 < 0 and num2 < 0: print("same sign")
if num1 > 0 and num2 > 0: print("same sign")
if num1 > 0 and num2 < 0: print("different sign")
if num1 < 0 and num2 > 0: print("different sign")
Solution 1:[1]
You can use subtract the number by itself and if the result equal to zero in the two numbers or non equal to zero is the two numbers then it is the same sign, else different sign, here is the code:
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
if num1 + 0 - num1 == 0 and num2 + 0 - num2 == 0: print("same sign") # +
elif num1 + 0 - num1 != 0 and num2 + 0 - num2 != 0: print("same sign") # -
else: print("different sign")
Solution 2:[2]
Well, mb not the prettiest solution, but have a check
#!/usr/bin/env python3
num1 = 10
num2 = 2
if ((num1 & 0x800000) == (num2 & 0x800000)):
print('same sign')
else:
print('different sign')
the trick here, that int type in Python takes 24 bits = 3 bytes. Signed types have 1 in the most significant position. 0x800000 = 1000 0000 0000 0000 0000 0000b. If both nums have this bit - same sign, otherwise - different.
Solution 3:[3]
You can check whether two numbers x and y have the same sign by validating the following:
same_sign = abs(x) + abs(y) == abs(x + y)
Solution 4:[4]
A little late here, but this is what I figured out.
def sameSign(x, y)
if (x*y > 0):
print("same sign")
else:
print("different sign")
Negative times negative and positive time positive both always give positive. Negative time positive gives negative. If you pass in zero, you always get false, so you could add a check.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | Ryan |
