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

后端 未结 22 1659
情书的邮戳
情书的邮戳 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:33

    In C, with bitwise operators:

    #include
    
    int add(int x, int y) {
        int a, b;
        do {
            a = x & y;
            b = x ^ y;
            x = a << 1;
            y = b;
        } while (a);
        return b;
    }
    
    
    int main( void ){
        printf( "2 + 3 = %d", add(2,3));
        return 0;
    }
    

    XOR (x ^ y) is addition without carry. (x & y) is the carry-out from each bit. (x & y) << 1 is the carry-in to each bit.

    The loop keeps adding the carries until the carry is zero for all bits.

提交回复
热议问题