我来这里是为了寻找这个问题,我发现 Zengr 的答案是正确的。谢谢曾格!
但是我想看看有一个修改是在他的代码中去掉“+”运算符。这应该使用 NO ARITHMETIC OPERATORS 将两个任意数字相乘,但都是按位。
Zengr 的解决方案优先:
#include<stdio.h>
main()
{
int a,b,result;
printf("nEnter the numbers to be multiplied :");
scanf("%d%d",&a,&b); // a>b
result=0;
while(b != 0) // Iterate the loop till b==0
{
if (b&01) // Bitwise & of the value of b with 01
{
result=result+a; // Add a to result if b is odd .
}
a<<=1; // Left shifting the value contained in 'a' by 1
// multiplies a by 2 for each loop
b>>=1; // Right shifting the value contained in 'b' by 1.
}
printf("nResult:%d",result);
}
我的答案是:
#include<stdio.h>
main()
{
int a,b,result;
printf("nEnter the numbers to be multiplied :");
scanf("%d%d",&a,&b); // a>b
result=0;
while(b != 0) // Iterate the loop till b==0
{
if (b&01) // Bitwise & of the value of b with 01
{
result=add(result,a); // Add a to result if b is odd .
}
a<<=1; // Left shifting the value contained in 'a' by 1
// multiplies a by 2 for each loop
b>>=1; // Right shifting the value contained in 'b' by 1.
}
printf("nResult:%d",result);
}
我会将 add() 写为:
int Add(int x, int y)
{
// Iterate till there is no carry
while (y != 0)
{
// carry now contains common set bits of x and y
int carry = x & y;
// Sum of bits of x and y where at least one of the bits is not set
x = x ^ y;
// Carry is shifted by one so that adding it to x gives the required sum
y = carry << 1;
}
return x;
}
或递归添加为:
int Add(int x, int y)
{
if (y == 0)
return x;
else
return Add( x ^ y, (x & y) << 1);
}
添加代码来源:http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/