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

前端 未结 30 1534
别跟我提以往
别跟我提以往 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:37

    When it comes down to it, multiplication by a positive integer can be done like this:

    int multiply(int a, int b) {
      int ret = 0;
      for (int i=0; i

    Efficient? Hardly. But it's correct (factoring in limits on ints and so forth).

    So using a left-shift is just a shortcut for multiplying by 2. But once you get to the highest power-of-2 under b you just add a the necessary number of times, so:

    int multiply(int a, int b) {
      int ret = a;
      int mult = 1;
      while (mult <= b) {
        ret <<= 1;
        mult <<= 1;
      }
      while (mult < b) {
        ret += a;
      }
      return ret;
    }
    

    or something close to that.

    To put it another way, to multiply by 7.

    • Left shift by 2 (times 4). Left shift 3 is 8 which is >7;
    • Add b 3 times.

提交回复
热议问题