LeetCode Q371 Sum of Two Integers(Easy)

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 ^ 1 = 0, 1 ^ 0 = 1, 0 ^ 1 = 1, 0 ^ 0 =0)。

  但有一个问题,就是进位。先算出进位的值(就是在异或条件下,比正确答案小的值),然后再相加,直到没有进位。

 1 public class Solution 
 2 {
 3     public int GetSum(int a, int b) 
 4     {
 5         int result = a ^ b;
 6         int carry = (a & b) << 1;
 7         if (carry == 0) return result;
 8         return GetSum(result, carry);
 9     }
10 }

 

原文地址:https://www.cnblogs.com/Bita/p/5938530.html