首页 > 其他 > 详细

371. Sum of Two Integers

时间:2016-07-06 13:12:08      阅读:212      评论:0      收藏:0      [点我收藏+]

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来得到两数和不需要进位的位。  //^异或(XOR)

2、能用a&b来得到两数和需要进位的位,(a&b)<<1+a^b就是Sum。

3、把(a&b)<<1和a^b作为参数,递归调用getSum,直到参数a等于零,返回两数和。

1 class Solution {
2 public:
3     int getSum(int a, int b) {
4         if(a==0)return b;
5         return getSum((a&b)<<1,a^b);
6     }
7 };    

 

371. Sum of Two Integers

原文:http://www.cnblogs.com/Z-Sky/p/5646532.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!