只应用位运算实现加减乘除是程序员的基本修养,这里应用通俗易懂的python实现加减乘除,其他语言同理。
应对python无限制扩展位数的方法
# 限制变量为32位
def int32(value):
return -(value & 0x80000000) | (value & 0x7FFFFFFF)
加法,本位+进位
def add(a, b):
while b:
carry = a & b
a = a ^ b
b = carry << 1
return a
减法,本位-借位
def subtract(a, b):
while b:
borrow = (~a) & b
a = a ^ b
b = borrow << 1
return a
乘法
def multiply(a, b):
result = 0
neg = a < 0 and b > 0 or a > 0 and b < 0
a, b = abs(a), abs(b)
while b:
if b & 1:
result = add(result, a)
a <<= 1
b >>= 1
return -result if neg else result
除法
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
neg = a < 0 and b > 0 or a > 0 and b < 0
a, b = abs(a), abs(b)
result = 0
while a >= b:
temp, i = b, 1
while a >= (temp << 1):
temp <<= 1
i <<= 1
a = subtract(a, temp)
result = add(result, i)
return -result if neg else result