首页 > 其他 > 详细

Sum of Two Integers

时间:2016-11-01 07:37:57      阅读:215      评论: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 class Solution {
 2 public:
 3     int getSum(int a, int b) {
 4         int base = 0, result = 0, carry = 0;
 5         while (base < 32) {
 6             // get the last bit of a and b, xor with carry
 7             int tempA = a & 1, tempB = b & 1;
 8             int current = (tempA ^ tempB ^ carry) << base;
 9             result |= current;
10             carry = (tempA & tempB) || (tempA & carry) || (tempB & carry);
11             a >>= 1;
12             b >>= 1;
13             base++;
14         }
15         return result;
16     }
17 };

 

Sum of Two Integers

原文:http://www.cnblogs.com/amazingzoe/p/6018125.html

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