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

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

    Was working on this problem myself in C# and couldn't get all test cases to pass. I then ran across this.

    Here is an implementation in C# 6:

    public int Sum(int a, int b) => b != 0 ? Sum(a ^ b, (a & b) << 1) : a;
    

提交回复
热议问题