首页 > 其他 > 详细

371. Sum of Two Integers

时间:2016-07-21 00:38:47      阅读:136      评论:0      收藏: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.
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. 把前两个步骤的结果相加。该相加的过程依然重复前两步,直到不产生进位为止。

 

371. Sum of Two Integers

原文:http://www.cnblogs.com/whl2012/p/5690159.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!