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

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

    CMS's add() function is beautiful. It should not be sullied by unary negation (a non-bitwise operation, tantamount to using addition: -y==(~y)+1). So here's a subtraction function using the same bitwise-only design:

    int sub(int x, int y) {
        unsigned a, b;
        do {
            a = ~x & y;
            b =  x ^ y;
            x = b;
            y = a << 1;
        } while (a);
        return b;
    }
    

提交回复
热议问题