OJ:lintcode A + B 问题

作者: DayDayUpppppp | 来源:发表于2017-02-18 16:06 被阅读10次

    给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。
    注意事项
    你不需要从输入流读入数据,只需要根据aplusb的两个参数a和b,计算他们的和并返回就行。
    您在真实的面试中是否遇到过这个题?
    Yes
    说明
    a和b都是 32位 整数么?
    是的
    我可以使用位运算符么?
    当然可以
    样例
    如果 a=1 并且 b=2,返回3

    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;
            }
            else{
                int x1=a^b;
                int x2=a&b;
                aplusb(x1,x2<<1);
            }
            
        }
    };
    

    相关文章

      网友评论

        本文标题:OJ:lintcode A + B 问题

        本文链接:https://www.haomeiwen.com/subject/hizrwttx.html