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

后端 未结 21 1901
南笙
南笙 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;
    }
    
    0 讨论(0)
  • 2020-11-27 11:29

    All arithmetic operations decompose to bitwise operations to be implemented in electronics, using NAND, AND, OR, etc. gates.

    Adder composition can be seen here.

    0 讨论(0)
  • 2020-11-27 11:29

    Here is a compact C solution. Sometimes recursion is more readable than loops.

    int add(int a, int b){
        if (b == 0) return a;
        return add(a ^ b, (a & b) << 1);
    }
    
    0 讨论(0)
  • 2020-11-27 11:30

    The following would work.

    x - (-y)
    
    0 讨论(0)
  • 2020-11-27 11:31
    int Add(int a, int b)
    {
        while (b)
        {
            int carry = a & b;
            a = a ^ b;
            b = carry << 1;
        }
        return a;
    }
    
    0 讨论(0)
  • 2020-11-27 11:31

    You could transform an adder circuit into an algorithm. They only do bitwise operations =)

    0 讨论(0)
提交回复
热议问题