我在接受采访时被问到这个问题:
如何在不使用'+'运算符的情况下添加两个变量?
面试官问我,我无法回答,即使我是一名优秀的C程序员!
答案 0 :(得分:3)
使用按位运算符,您可以添加两个数字。请尝试以下:
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;
}