简体   繁体   中英

(Python Challenge) comparing signs of 2 numbers without using < or >

I've been stuck on this problem I found on a challenge site for awhile now. Little help? Basically 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 edit: ALSO you can 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")

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.

您可以通过验证以下内容来检查两个数字xy是否具有相同的符号:

same_sign = abs(x) + abs(y) == abs(x + y)

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM