[leetcode]: 371. Sum of Two Integers

我就是我 2022-06-16 01:25 218阅读 0赞

1.题目描述
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.

2.分析
首先想到电路里面加法器的实现:
保留位remain=a^b 0^1=1,1^0=1,0^0=0,1^1=0
进位carry=a&b<<1

3.代码

  1. class Solution {
  2. public:
  3. int getSum(int a, int b) {
  4. int remain = a;
  5. int carry = b;
  6. while (carry) {
  7. int temp = carry^remain;//异或
  8. carry = (carry&remain) << 1;//进位
  9. remain = temp;
  10. }
  11. return remain;
  12. }
  13. };

发表评论

表情:
评论列表 (有 0 条评论,218人围观)

还没有评论,来说两句吧...

相关阅读