0
// Function for multiplication 
int multiply(int n, int m) 
{   
    int ans = 0, count = 0; 
    while (m) 
    { 
        if (m % 2 == 1)               
            ans += n << count; 

        // increment of place value (count) 
        count++; 
        m /= 2; 
    } 
    return ans; 
} 

What does that expression mean? How to rewrite this expression in a more beginner friendly form?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Joshua Leung
  • 2,219
  • 7
  • 29
  • 52
  • To make it more beginner friendly, just do one operation per line. Store the result of `n << count` in a temporary variable and them `+=` it to `ans`. – Paul Rooney Sep 20 '19 at 03:36
  • 2
    Possible duplicate of [What are bitwise shift (bit-shift) operators and how do they work?](https://stackoverflow.com/questions/141525/what-are-bitwise-shift-bit-shift-operators-and-how-do-they-work) – phuclv Sep 20 '19 at 03:42

2 Answers2

3

The expression ans += n << count; means the same as the following:

int n_shifted = n << count;  /* bitshift n to the left by count bits */
ans = ans + n_shifted;       /* add n_shifted to ans */
Elias
  • 913
  • 6
  • 22
1

it bitshifts n left by count then adds it to ans

n << 1  =   n * 2
n << 2  =   n * 4
n << 3  =   n * 8
n << 4  =   n * 16

etc

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156