will left shift will in multiplication?

The Gateway to Computer Science Excellence

First time here? Checkout the FAQ!

x

+14 votes

Consider the function func shown below:

int func(int num) { int count = 0; while (num) { count++; num>>= 1; } return (count); }

The value returned by func($435$) is ________

+23 votes

Best answer

Answer is $9$.

$435-(110110011) $

num $>>=$ $1$; implies a num is shifted one bit right in every while loop execution.While loop is executed $9$ times successfully and $10$th time num is zero.

So count is incremented $9$ times.

**Note:**

Shifting a number `"1"`

bit position to the right will have the effect of dividing by $2$:

`8 >> 1 = $4 // In binary: (00001000) >> 1 = (00000100)`

+13 votes

int func(int num) // take decimal number { int count = 0; while (num) // until all bits are zero { count++; // count bit num>>= 1; // shift bits, removing lower bit } return (count); // returns total number of bits }

(435)_{10} = (110110011)_{2}

So, the given program counts total number of bits in binary representation . Hence, answer is 9

http://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer

+2 votes

The function mainly returns position of Most significant bit in binary representation of n. The MSD in binary representation of 435 is 9th bit.

**Another explanation **: >> in right shift. In other words, it means divide by 2. If keep on dividing by 2, we get: 435, 217, 108, 54, 27, 13, 6, 3, 1. Therefore, the count is 9.

- All categories
- General Aptitude 1.8k
- Engineering Mathematics 7.3k
- Digital Logic 2.9k
- Programming & DS 4.9k
- Algorithms 4.3k
- Theory of Computation 6k
- Compiler Design 2.1k
- Databases 4.1k
- CO & Architecture 3.4k
- Computer Networks 4.1k
- Non GATE 1.4k
- Others 1.4k
- Admissions 596
- Exam Queries 577
- Tier 1 Placement Questions 23
- Job Queries 72
- Projects 18

49,541 questions

54,071 answers

187,187 comments

70,978 users