Skip to content

Latest commit

 

History

History
37 lines (29 loc) · 732 Bytes

随笔-两整数之和.md

File metadata and controls

37 lines (29 loc) · 732 Bytes

题目:不使用运算符 + 和 - ​​​​​​​,计算两整数 ​​​​​​​a 、b ​​​​​​​之和。

示例 1:

输入: a = 1, b = 2 输出: 3 示例 2:

输入: a = -2, b = 3 输出: 1

思路:异或为两个数无进位相加;相与左移为两个数进位;

常规解法:

class Solution {
    public int getSum(int a, int b) {
        
        while(b!=0){
          int sum=a^b; //无进位相加;
          b=(a&b)<<1;  //有进位相加,左移;
          a=sum;  
        }
        return a;
    }
}

递归解法:

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