剑指offer-python 65 不用加减乘除做加法

写一个函数,求两个整数之和,要求不得使用 +、-、*、/ 四则运算符号。

解题思路

class Solution:
    def Add(self, num1, num2):
        # write code here
        return sum([num1,num2])

a ^ b 表示没有考虑进位的情况下两数的和,(a & b) << 1 就是进位。
递归会终止的原因是 (a & b) << 1 最右边会多一个 0,那么继续递归,进位最右边的 0 会慢慢增多,最后进位会变为 0,递归终止。

python中负数的二进制编码比较特殊

# 可以处理整数的加法,但不能处理负数
class Solution:
    def Add(self, num1, num2):
        # write code here
        return num1 if num2 == 0 \
        else self.Add(num1 ^ num2, (num1 & num2) << 1)

可以用 ctypes 来在 Python 中定义 C 语言的数据类型:

class Solution:

    def Add(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        import ctypes
        a = ctypes.c_int32(a).value
        b = ctypes.c_int32(b).value
        while b != 0:
            carry = ctypes.c_int32(a & b).value
            a = ctypes.c_int32(a ^ b).value
            b = ctypes.c_int32(carry << 1).value

        return a
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值