【leetcode】371. Sum of Two Integers

题目描述:

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

解题分析:

这种类型的题必然要用位运算,虽然自己写了关于位运算的代码,但是不够简洁。

后来参考了这篇博文:

http://blog.csdn.net/zhongjiekangping/article/details/6855864

这篇博文对位运算加法的实现讲的得十分清楚,我这里就只放按此思路写的实现代码了。

具体代码:

 1 public class Solution {
 2     public int getSum(int num1, int num2) {
 3         //执行加法
 4         int n=num1^num2; 
 5         //执行进位操作
 6         int m=(num1&num2)<<1; 
 7         //必须保证没有进位了,才能结束操作,否则重复上面的操作
 8         if(m!=0)
 9             return getSum(n,m);
10             
11         return n;
12     }
13 }
原文地址:https://www.cnblogs.com/godlei/p/5642144.html