Sum of Two Integers

在LeetCode OJ 上刷的第一道题目。

原题:

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.

首先,我第一想法是使用++来完成。

class Solution {
public:
    int getSum(int a, int b) {
        int temp = 0;
        if(a>0)
        {
            for(int i=0;i<a;i++)
            {
                temp++;
            }
        }
        else
        {
            for(int i=0;i>a;i--)
            {
                temp--;
            }
        }
        if(b>0)
        {
            for(int j=0;j<b;j++)
            {
                temp++;
            }
        }
        else
        {
            for(int j=0;j>b;j--)
            {
                temp--;
            }
        }
        return temp;
        
    }
};

 结果报出了:Time Limit Exceeded 的错误。在原基础上多次修改发现都不行,在度娘的帮助下,学习到了二进制处理加法的方法。

参考:http://blog.csdn.net/lalor/article/details/7366371

下面说下我自己的理解。

首先,先对数据a,b进行&(与)运算,原因是下面用^(异或)的方法来进行加法会漏掉进位,所以,先对数据进行&运算得到carry,carry中为1的位是会进行进位的位,接下来对数据进行^运算,结果记为add1,实现伪加法,之所以是伪加法,是因为它漏掉了进位。那漏掉的进位怎么办呢?对carry进行左移得到C,C+add1就是两个数据的真正的和。那怎么实现C+add1呢?将add1赋予a,C赋予b,重复以上的操作,直到b等于0.

原文地址:https://www.cnblogs.com/yns-blogs/p/5641888.html