Lintcode A+B问题

来源:互联网 发布:java中转义字符 编辑:程序博客网 时间:2024/05/16 04:56

问题描述

  • 给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

注意事项

你不需要从输入流读入数据,只需要根据aplusb的两个参数a和b,计算他们的和并返回就行。

说明
a和b都是 32位 整数么?

是的
我可以使用位运算符么?

当然可以
样例
如果 a=1 并且 b=2,返回3

笔记

《加法》,可以拆分成《异或得到的“加法不进位”》与《相与左移1的进位》的《加法》,因此,每次递归中都进行异或、相与左移1,然后,将得到的结果再做同样的操作,直到进位为0,递归停止。

代码

  • 递归
class Solution {public:    /*     * @param a: The first integer     * @param b: The second integer     * @return: The sum of a and b     */    int aplusb(int a, int b) {        // write your code here, try to do it without arithmetic operators.        if (b == 0)            return a;        int nocarry = a ^ b;        int carry = (a & b) << 1;        return aplusb(nocarry, carry);    }};
  • 循环
class Solution {public:    /*     * @param a: The first integer     * @param b: The second integer     * @return: The sum of a and b     */    int aplusb(int a, int b) {        // write your code here, try to do it without arithmetic operators.        while (b != 0)        {            int tmpa = a ^ b;            int tmpb = (a & b) << 1;            a = tmpa;            b = tmpb;        }        return a;    }};
0 0
原创粉丝点击