這還挺有趣:)我不知道這是否是你追求的,但只要這些都應該按照您正在使用整數
def subtract(a, b):
if a < 0:
return negative(add(negative(a), b))
if b < 0:
return add(a, negative(b))
if a < b:
return negative(subtract(b, a))
if b == 0:
return a
return subtract(a^b, (~a & b) << 1)
def negative(a):
if a == 0: return 0
a = ~a
b = 1
while b > 0:
a, b = a^b, (a&b) << 1
return a
def add(a, b):
if a < 0:
return negative(subtract(negative(a), b))
if b < 0:
return subtract(a, negative(b))
if b == 0:
return a
return add(a^b, (a & b) << 1)
def multiply(a, b):
if a == 0 or b == 0:
return 0
if b < 0:
a = negative(a)
b = negative(b)
A = 0
while b > 0:
A = add(A, a)
b = subtract(b, 1)
return A
def div(a, b):
if b == 0:
raise ZeroDivisionError
if a == 0:
return 0
if b < 0:
a = negative(a)
b = negative(b)
A = 0
if a < 0:
while a < 0:
a = add(a, b)
A = subtract(A, 1)
else:
while b < a :
a = subtract(a, b)
A = add(A, 1)
return A
def mod(a, b):
return subtract(a, multiply(div(a, b),b))
通過two's compliment否定用來得到一個函數,其中a和b都大於0,並選擇正確的操作(加法或減法)。進一步用減法,注意不要產生負面結果。這是因爲遞歸定義的加減仇恨交叉0.同樣在這種情況下,遞歸加法和減法完成與你的循環完全相同的事情。
爲什麼你要做這樣的事情呢? –
這是一個leetcode問題,但我無法獲得正確的代碼。 (悲傷的臉) –
爲什麼不只是'返回一個 - -b'? –