This question already has answers here:
Closed 3 years ago.
Add two integers using only bitwise operators?
(7个答案)
How to add two numbers without using ++ or + or another arithmetic operator
(20个答案)
我在一次采访中被问到这个问题:
如何在不使用“+”运算符的情况下添加两个变量?
面试官问我,我答不上来,尽管我是个优秀的C程序员!
使用递增和递减运算符可以添加两个数字。
另一种可能是:
(7个答案)
How to add two numbers without using ++ or + or another arithmetic operator
(20个答案)
我在一次采访中被问到这个问题:
如何在不使用“+”运算符的情况下添加两个变量?
面试官问我,我答不上来,尽管我是个优秀的C程序员!
最佳答案
使用按位运算符可以添加两个数字。请尝试以下操作:
int Sum(int a, int b)
{
// Iterate till there is no carry
while (b != 0)
{
// now carry contains common set bits of a and b
int carry = a & b;
// Sum of bits of a and b where at least one of the bits is not set
a = a ^ b;
// Carry is shifted by one so that adding it to a gives the required sum
b = carry << 1;
}
return a;
}
使用递增和递减运算符可以添加两个数字。
另一种可能是:
int Sum(int a, int b)
{
// Iterate till there b becomes zero
while (b--)
{
a++;
}
return a;
}
09-30 21:54