首页 > 代码库 > Sum of Two Integers
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。