371. Sum of Two Integers

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.
Tags:Bit Manipulation
Similar Problems: (M) Add Two Numbers

2. 解题思路

  • 对数字做运算,除了四则运算,也就只剩下位运算啦!
  • 此题目正好类同《剑指offer》中的【面试题 47】,具体思考过程可参考《剑指offer》!

3. 代码

 1 class Solution {
 2 public:
 3     int getSum(int a, int b) 
 4     {
 5         while (b)
 6         {
 7             int sum = a ^ b;
 8             int carray = (a & b) << 1;
 9             a = sum; 
10             b = carray;
11         }
12         return a;
13     }
14 };

4. 反思

  • 半加法思想:
    • Step 1. 不考虑进位,对每一位相加。--->可通过 异或 运算实现。
    • Step 2. 考虑进位。--->可通过 与 运算实现。
    • Step 3. 把前两个步骤的结果相加。该相加的过程依然重复前两步,直到不产生进位为止。
原文地址:https://www.cnblogs.com/whl2012/p/5690159.html