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

Sum of Two Integers

时间:2016-11-01 07:39:33      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:current   get   nbsp   opera   result   ++   turn   blog   color   

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

标签:current   get   nbsp   opera   result   ++   turn   blog   color   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!