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

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

    int multiply(int multiplicand, int factor)
    {
        if (factor == 0) return 0;
    
        int product = multiplicand;
        for (int ii = 1; ii < abs(factor); ++ii) {
            product += multiplicand;
        }
    
        return factor >= 0 ? product : -product;
    }
    

    You wanted multiplication without *, you got it, pal!

提交回复
热议问题