1. A + B 问题

思路

模拟二进制计算
1.先转化为2个二进制数
2.二进制数相加,因为加法结合律 (a + b) + c = a + (b + c) 推出 a + b = (a - c) + (b - d) + (c + d)
3.采用^ 和 & 来获得两个数的 相加不进位的结果(a ^ b) 和 只进位的结果((a & b) << 1)
4.结合2和3,通过拆分数字可以得到 a + b = (a 相加不进位 b) + (a 只进位 b) = (a ^ b) + ((a & b) << 1)
^
0 0 = 0
0 1 = 1
1 0 = 1
1 1 = 0
&
0 0 = 0
0 1 = 0
1 0 = 0
1 1 = 1
eg:
2 + 3 = 5
0 0 1 0
0 0 1 1
-------
0 1 0 1
2 ^ 3 = 0 0 0 1 = 1
2 & 3 = 0 0 1 0 = 2 (向左进一位,加法进位)
2 + 3 = 1 + 4
0 0 0 1
0 1 0 0
-------
0 1 0 1
1 ^ 4 = 0 1 0 1 = 5
1 & 4 = 0 0 0 0 = 0
1 + 4 = 0 + 5
plus(2, 3) = plus(2 ^ 3, (2 & 3) << 1) = plus(1, 4)
plus(1 ,4) = plus(5, 0)
递归,确定递归出口

Python

class Solution:
    """
    @param: : An integer
    @param: : An integer
    @return: The sum of a and b
    """

    def aplusb(self, a, b):
        # write your code here
        # 递归
        # return a if not b else aplusb(a ^ b, (a & b) << 1)
        # 循环
        import ctypes
        while b:
            tmp = ctypes.c_int32(a & b).value << 1
            res = a ^ b
            a = res
            b = tmp
        else:
            return a


if __name__ == '__main__':
    s = Solution()
    print(s.aplusb(8, -4))

Go

package main

import "fmt"

/**
 * @param a: An integer
 * @param b: An integer
 * @return: The sum of a and b
 */
func aplusb(a int, b int) int {
    // write your code here
    for {
        if b == 0 {
            return a
        } else {
            return aplusb(a^b, (a&b)<<1)
        }
    }
}

func main() {
    fmt.Println(aplusb(2, 4))
    fmt.Println(aplusb(3, 5))
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值