【LintCode】1、A + B问题

版权声明:本文为博主原创文章,如需转载,请注明地址:http://blog.csdn.net/sunkun2013 https://blog.csdn.net/u010043538/article/details/77746308

1、题目:A + B 问题

原题链接:http://www.lintcode.com/zh-cn/problem/a-b-problem/

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

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

样例:
如果 a=1 并且 b=2,返回3

2、分析

无法使用+,可以使用位运算符

a ^ b //可以看做不进位加法
a & b // 可以看做只算进位结果。

3、AC代码

public class Solution {
    /*
     * @param a: An integer
     * @param b: An integer
     * @return: The sum of a and b
     */
    public int aplusb(int a, int b) {
        // write your code here
        while (b != 0) {
            int a_temp = a ^ b;
            int b_temp = (a & b) << 1;
            a = a_temp;
            b = b_temp;
        }
        return a;
    }
}

猜你喜欢

转载自blog.csdn.net/u010043538/article/details/77746308