写一个函数,求两个整数的之和,要求在函数体内不得使用+、-、×、÷。
int sum(int a, int b)
{
int result = 0;
int factor = 1;
int c = 0;
while ((a != 0) || (b != 0))
{
if ((a&factor) == 0 && (b&factor) == 0)
{
if (c)
{
result |= factor;
c = 0;
}
}
else
{
if ((a&factor) && (b&factor))
{
if (c == 0)
{
c = 1;
}
else
{
result |= factor;
}
}
else
{
if (c == 0)
{
result |= factor;
}
}
}
a &= (~factor);
b &= (~factor);
factor <<= 1;
}
if (c)
{
result |= factor;
}
return result;
}