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

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

    Think about the normal multiplication method we use

             1101 x        =>13
             0101          =>5
    ---------------------
             1101
            0000
           1101
          0000
    ===================        
          1000001 .        => 65
    

    Writing the same above in the code

    #include
    
    int multiply(int a, int b){
        int res = 0,count =0;
        while(b>0) {
            if(b & 0x1)
                res = res + (a << count);
            b = b>>1;
            count++;
        }
        return res;
    }
    int main() {
        printf("Sum of x+y = %d", multiply(5,10));
        return 0;
    }
    

提交回复
热议问题