What is the best way to add two numbers without using the + operator?

后端 未结 22 1703
情书的邮戳
情书的邮戳 2020-11-27 05:18

A friend and I are going back and forth with brain-teasers and I have no idea how to solve this one. My assumption is that it\'s possible with some bitwise operators, but n

22条回答
  •  佛祖请我去吃肉
    2020-11-27 05:36

    You can do it using bit-shifting and the AND operation.

    #include 
    
    int main()
    {
        unsigned int x = 3, y = 1, sum, carry;
        sum = x ^ y; // Ex - OR x and y
        carry = x & y; // AND x and y
        while (carry != 0) {
            carry = carry << 1; // left shift the carry
            x = sum; // initialize x as sum
            y = carry; // initialize y as carry
            sum = x ^ y; // sum is calculated
            carry = x & y; /* carry is calculated, the loop condition is
                            evaluated and the process is repeated until
                            carry is equal to 0.
                            */
        }
        printf("%d\n", sum); // the program will print 4
        return 0;
    }
    

提交回复
热议问题