How can I perform multiplication without the '*' operator?

前端 未结 30 1505
别跟我提以往
别跟我提以往 2020-12-01 01:47

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

<
30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 02:42

    Any number, odd or even, can be expressed as a sum of powers of two. For example,

         1   2   4   8
    ------------------
     1 = 1
     2 = 0 + 2
     3 = 1 + 2
     4 = 0 + 0 + 4
     5 = 1 + 0 + 4
     6 = 0 + 2 + 4
     7 = 1 + 2 + 4
     8 = 0 + 0 + 0 + 8
    11 = 1 + 2 + 0 + 8
    

    So, you can multiply x by any number by performing the right set of shifts and adds.

     1x = x
     2x = 0 + x<<1
     3x = x + x<<1
     4x = 0 +  0   + x<<2
     5x = x +  0   + x<<2
    11x = x + x<<1 +   0  + x<<3
    

提交回复
热议问题