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

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

    @Wang, that's a good generalization. But here is a slightly faster version. But it assumes no overflow and a is non-negative.

    int mult(int a, int b){
        int p=1;
        int rv=0;
        for(int i=0; a >= p && i < 31; i++){
            if(a & p){
                rv += b;
            }
            p = p << 1;
            b = b << 1;
        }
    
        return rv;
    }
    

    It will loop at most 1+log_2(a) times. Could be faster if you swap a and b when a > b.

提交回复
热议问题