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

371. Sum of Two Integers

时间:2016-07-06 13:13:35      阅读:111      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!