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