[LintCode] A + B Problem(位运算)

Problem

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

Example

Given a=1 and b=2 return 3

Challenge

Of course you can just return a + b to get accepted. But Can you challenge not do it like that?

Note

**位运算笔记
Bit Manipulation Notes:**

加法:

  1. ^异或运算:求和;

  2. &与运算:进位。

减法:

  1. 将负数化为正:~i, +1,两步完成取反

  2. 做加法

乘法:

  1. a * b: if (b & 1) ans += a //b的最后一位是1,则结果+a

  2. 每次循环后a << 1, b >> 1; //b始终判断最后一位,a进位累加(小学生算式做乘法)

除法:(不赘述,O(log n))

http://blog.csdn.net/ojshilu/article/details/11179911

Solution

class Solution {
    public int aplusb(int a, int b) {
        // write your code here, try to do it without arithmetic operators.
        if (b == 0) return a;
        int sum = a^b;
        int carry = (a&b) << 1;
        return aplusb(sum, carry);
    }
}
    原文作者:位运算
    原文地址: https://segmentfault.com/a/1190000004419503
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞