Sum of Two Integers
Posted amazingzoe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sum of Two Integers相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
leetcode371. Sum of Two Integers
LeetCode之371. Sum of Two Integers
LeetCode: 371 Sum of Two Integers(easy)