Sum of Two Integers问题及解法

来源:互联网 发布:编程 数学 编辑:程序博客网 时间:2024/05/21 12:08

问题描述:

 Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

示例:

Given a = 1 and b = 2, return 3.


问题分析:

不用+和-,我们可以考虑从位运算的角度出发。主要用到了进位操作和异或运算.


过程详见代码:

class Solution {public:    int getSum(int a, int b) {        int res = a ^ b;        int flag = 0;        int jin = 0;        int i = 1,j = 1;        while(i++ <= 32)        {            jin = jin ^ flag;            flag = ((a & b & j) | (a & flag) | (b & flag));            flag <<= 1;            j <<= 1;        }         return (res ^ jin);    }};


0 0
原创粉丝点击