371. Sum of Two Integers

来源:互联网 发布:防晒霜推荐知乎 编辑:程序博客网 时间:2024/05/21 17:25

题目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.

Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

解题思路

  把二进制上的加法用位运算来替代.
  第一步不考虑进位,对每一位相加。0加0与1加1的结果都0,0加1与1加0的结果都是1。这和异或的运算结果是一致。
  第二步进位,对0加0、0加1、1加0而言,都不会产生进位,只有1加1时,会向前产生一个进位。此时我们可以想象成是两个数先做位与运算,然后再向左移动一位。只有两个数都是1的时候,位与得到的结果是1,其余都是0。
第三步把前两个步骤的结果相加

代码如下

class Solution {public:    int getSum(int a, int b) {        if (0 == b)            return a;        int sum = a ^ b;        int add = (a & b) << 1;        return getSum(sum, add);    }};

  1. https://leetcode.com/problems/sum-of-two-integers/ ↩
0 0
原创粉丝点击