/****************************************************************
題目:寫一個(gè)函數(shù),求兩個(gè)整數(shù)之和,要求在函數(shù)體內(nèi)不得使用+、-、*、/
四則運(yùn)算符號,
不用加減乘除做加法
。****************************************************************/
//對數(shù)字做運(yùn)算,除了四則運(yùn)算,就只剩下位運(yùn)算
#include
int Add(int num1, int num2)
{
int sum, carry;
do
{
sum = num1 ^ num2;
carry = (num1 & num2) << 1;
num1 = sum;
num2 = carry;
}
while(num2 != 0);
return num1;
}
// ====================測試代碼====================
void Test(int num1, int num2, int expected)
{
int result = Add(num1, num2);
if(result == expected)
printf("%d + %d is %d. Passed\n", num1, num2, result);
else
printf("%d + %d is %d. Failed\n", num1, num2, result);
}
int main()
{
Test(1, 2, 3);
Test(111, 899, 1010);
Test(-1, 2, 1);
Test(1, -2, -1);
Test(3, 0, 3);
Test(0, -4, -4);
Test(-2, -8, -10);
}