leetcode submission/20161012(sum of two integers)

来源:互联网 发布:淘宝订机票 编辑:程序博客网 时间:2024/05/01 04:03

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:

Given a = 1 and b = 2, return 3.

解题思路还是和之前算过的single number一样,利用进位原则:

1、输入 a,b 
2、按照位把ab相加,不考虑进位,结果是 a xor b,即1+1 =0 0+0 = 0 1+0=1
3、计算ab的进位的话,只有二者同为1才进位,因此进位可以标示为 (a and b) << 1 ,注意因为是进位,所以需要向左移动1位 
4、于是a+b可以看成 (a xor b)+ ((a and b) << 1),这时候如果 (a and b) << 1 不为0,就递归调用,因为(a xor b)+ ((a and b) << 1) 也有可能进位,所以我们需要不断的处理进位。


public class solution {

public int getSum(int a, int b) {

int xor = a^b;

int and = a&b<<1;

if (and != 0)

return getSum(xor, and);

return xor;

}

}


或者就一行

class Solution {
public:
    int getSum(int a, int b) {
        return (b == 0) ? a : getSum(a^b, (a&b)<<1);
    }
};


reference:http://www.cnblogs.com/grandyang/p/5631814.html 

0 0
原创粉丝点击