c - 编写一个不使用算术运算符将两个数字相乘的程序

标签 c

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/

相关文章:

c++ - 推荐哪个C/C++的跨平台UI框架...

c - snprintf 不使用 strftime 打印转换后的 timeval?

c - C 中的 block 中的 read() 和 write() 非文本文件

c - 如何查看我编译的机器语言/汇编代码?

c - = 的操作数具有非法类型

c - 如何创建静态链接共享库

c - TCP 套接字,服务器无法响应客户端,接受 : Interrupted system call

检查字符串是否为回文 - 当我编译程序时关闭

c - 如何从 C 中的父进程分离 fork 进程

c - 理解 C 中的语句