我在一次采访中被问到这个问题:
如何在不使用“+”运算符的情况下添加两个变量?
面试官问我,我不能回答,即使我是一个优秀的C程序员!
发布于 2016-10-14 13:34:53
使用按位的运算符,您可以添加两个数字。试着在下面:
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;
}https://stackoverflow.com/questions/40041811
复制相似问题