Possible Duplicate:
How to add two numbers without using ++ or + or another arithmetic operator.
是否可以编写一个程序(用 C 语言)在不使用任何算术运算符(*、+、-、/、%)的情况下将两个数字相乘。
最佳答案
如果您可以使用按位运算符进行加法,下面的代码片段可能会有所帮助
int xor, and, temp;
and = x & y;
xor = x ^ y;
while(and != 0 )
{
and <<= 1;
temp = xor ^ and;
and &= xor;
xor = temp;
}
a 和 b 相乘,加上“a”“b”次
unsigned int mult(unsigned int a,unsigned int b)
{
unsigned int counter=0;
unsigned int mult = a;
if(a == 0 || b == 0)
{
return 0;
}
//Optimize if any of the number is power of two then
//Just right shift other with value of this number
while(counter < b )
{
counter = add(counter,1);
mult = add(mult,a);
}
return mult;
}
关于c - 编写一个不使用算术运算符将两个数字相乘的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4756112/