Lintcode 1 A + B 问题 位运算

Write a function that add two numbers A and B. You should not use + or any arithmetic operators.

 Notice

There is no need to read data from standard input stream. Both parameters are given in function aplusb, you job is to calculate the sum and return it.

Clarification

Are a and b both 32-bit integers?

  • Yes.

Can I use bit operation?

  • Sure you can.
Example

Given a=1 and b=2 return 3

此题考查的是位计算(亦或运算)

思路:
考虑一个普通的加法计算:5+17=22

在十进制加法中可以分为如下3步进行:
    1. 忽略进位,只做对应各位数字相加,得到12(个位上5+7=12,忽略进位,结果2);
    2. 记录进位,上一步计算中只有个位数字相加有进位1,进位值为10;
    3. 按照第1步中的方法将进位值与第1步结果相加,得到最终结果22。

下面考虑二进制数的情况(5=101,17=10001):
仍然分3步:
    1. 忽略进位,对应各位数字相加,得到10100;
    2. 记录进位,本例中只有最后一位相加时产生进位1,进位值为10(二进制);
    3. 按照第1步中的方法将进位值与第1步结果相加,得到最终结果10110,正好是十进制数22的二进制表示。

接下来把上述二进制加法3步计算法用位运算替换:
    第1步(忽略进位):0+0=0,0+1=1,1+0=0,1+1=0,典型的异或运算。
    第2步:很明显,只有1+1会向前产生进位1,相对于这一数位的进位值为10,而10=(1&1)<<1。
    第3步:将第1步和第2步得到的结果相加,其实又是在重复这2步,直到不再产生进位为止。

代码如下:

class Solution {
public:
    /*
     * @param a: The first integer
     * @param b: The second integer
     * @return: The sum of a and b
     */
    int aplusb(int a, int b) {
        // write your code here, try to do it without arithmetic operators.
        int carry = 0;
        while (b)
        {
            carry = a & b;
            a = a ^ b;
            b = carry << 1;
        }
        
        return a;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值