How to add two numbers without using ++ or + or another arithmetic operator

后端 未结 21 2043
南笙
南笙 2020-11-27 10:48

How do I add two numbers without using ++ or + or any other arithmetic operator?

It was a question asked a long time ago in some campus interview. Anyway, today some

21条回答
  •  醉梦人生
    2020-11-27 11:40

    This can be done recursively:

    int add_without_arithm_recursively(int a, int b)
    {
        if (b == 0) 
            return a;
    
        int sum = a ^ b; // add without carrying
        int carry = (a & b) << 1; // carry, but don’t add
        return add_without_arithm_recursively(sum, carry); // recurse
    }
    

    or iteratively:

    int add_without_arithm_iteratively(int a, int b)
    {
        int sum, carry;
    
        do 
        {
            sum = a ^ b; // add without carrying
            carry = (a & b) << 1; // carry, but don’t add
    
            a = sum;
            b = carry;
        } while (b != 0);
    
        return a;
    }
    

提交回复
热议问题