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

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

    public static int multiply(int a, int b) 
    {
        int temp = 0;
        if (b == 0) return 0;
        for (int ii = 0; ii < abs(b); ++ii) {
            temp = temp + a;
        }
    
        return b >= 0 ? temp : -temp;
    }
    
    public static int abs(int val) {
    
        return val>=0 ? val : -val;
    }
    

提交回复
热议问题