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

后端 未结 21 2116
南笙
南笙 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:24

    Without using any operators adding two integers can be done in different ways as follows:

    int sum_of_2 (int a, int b){
       int sum=0, carry=sum;
       sum =a^b;
       carry = (a&b)<<1;
       return (b==0)? a: sum_of_2(sum, carry);
    }
    // Or you can just do it in one line as follows:
    int sum_of_2 (int a, int b){
       return (b==0)? a: sum_of_2(a^b, (a&b)<<1);
    }
    // OR you can use the while loop instead of recursion function as follows
    int sum_of_2 (int a, int b){
        if(b==0){
           return a;
       }
       while(b!=0){
         int sum = a^b;
         int carry = (a&b)<<1;
         a= sum;
         b=carry;
      }
      return a;
    }
    

提交回复
热议问题