371. Sum of Two Integers

来源:互联网 发布:isp图像处理编程 编辑:程序博客网 时间:2024/05/01 05:33

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.

思路:a^b异或等于无进位的加法,(a&b)<<1等于进位,两者一直相加,直到进位为零。

解法一:

public class Solution {    public int getSum(int a, int b) {        int sum=0, carry=0;        while(b!=0){            sum = a^b;            carry = (a&b)<<1;            a = sum;            b = carry;        }        return a;    }}
解法二:
public class Solution {    public int getSum(int a, int b) {        if(b==0) return a;        return getSum(a^b, (a&b)<<1);    }}


0 0
原创粉丝点击