码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Sum of Two Integers

时间:2018-04-28 14:17:04      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:and   左移   code   不为   判断   car   sum   处理   solution   

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.

 

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) 也有可能进位,所以我们需要不断的处理进位。

 

class Solution {
    public int getSum(int a, int b) {
        int result = a ^ b; // 按位加
        int carray = (a & b) << 1; // 计算进位
        if(carray!=0) return  getSum(result,carray); //判断进位与处理
        return result;
    }
}

 

LeetCode - Sum of Two Integers

标签:and   左移   code   不为   判断   car   sum   处理   solution   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/8966502.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!