我怎么能不带“*”操作符执行乘法? [英] How can I perform multiplication without the '*' operator?

查看:105
本文介绍了我怎么能不带“*”操作符执行乘法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正要通过一些基本的东西,因为我学习C.我来到一个问题了7,而无需使用*操作符乘以一个数字。基本上是这样的。

I was just going through some basic stuff as I am learning C. I came upon a question to multiply a number by 7 without using the * operator. Basically it's like this

      (x << 3) - x;

现在我知道基本的位操作,​​但我不能让你怎么通过任何其他奇数不使用*运算乘以多少?是否有一个通用的算法呢?

Now I know about basic bit manipulation operations, but I can't get how do you multiply a number by any other odd number without using the * operator? Is there a general algorithm for this?

推荐答案

考虑使用铅笔和纸十进制如何繁殖:

Think about how you multiply in decimal using pencil and paper:

  12
x 26
----
  72
 24
----
 312

这是什么乘法样子二进制?

What does multiplication look like in binary?

   0111
x  0101
-------
   0111
  0000
 0111
-------
 100011

注意什么?不像乘法小数,你需要在列表中加数把它写下来之前,记住了乘法表,以二进制倍增时,你总是由0或1相乘的条款之一。有不需要时间表。如果第二个任期内的数字是1,你的第一项补充。如果它是0,你不知道。还注意到加数是如何逐步偏移到左边。

Notice anything? Unlike multiplication in decimal, where you need to memorize the "times table," when multiplying in binary, you are always multiplying one of the terms by either 0 or 1 before writing it down in the list addends. There's no times table needed. If the digit of the second term is 1, you add in the first term. If it's 0, you don't. Also note how the addends are progressively shifted over to the left.

如果你不能确定这一点,做纸几个二进制乘法。当您完成后,转换结果返回给小数,看看它是否是正确的。你已经做了一些之后,我想你会得到的想法二进制乘法如何实现使用转移,并增加了。

If you're unsure of this, do a few binary multiplications on paper. When you're done, convert the result back to decimal and see if it's correct. After you've done a few, I think you'll get the idea how binary multiplication can be implemented using shifts and adds.

这篇关于我怎么能不带“*”操作符执行乘法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆