What does the following function do ie what does the value o

What does the following function do (i.e. what does the value of x represent at the end)?

What does the following function do (i.e. what does the value of x represent at the end)? unsigned strange (unsigned int k) { unsigned int x = 0; while(k) { k = k & (k-1); x++; } return x; }

Solution

Output : The function takes an unsigned input number and returns number of one’s in the input number of binary format .

Ex : input value k= 5

On this input, the function performs bitwise operation with preceeding number and stores result in k.This process is performed untill the k value is 0.

Bitwise operation is performed on binary formate only.

i.e)

Initially x=0

Itaration 1 :Binary formate of k=5 is 101

                Binary format of k-1=4 is   100

                   Result of k & K-1 is           100   //this value assigned to k

                    Now   x is incrementd –> x=1     // increments x and repeats the loop because k is not zero

Itaration 2 :Binary formate of k=4 is 100

                Binary format of k-1=3 is   011

                   Result of k & K-1 is           000   //this value assigned to k now and stop the loop because k is zero

                    Now   x is incrementd –> x=2    // stop the loop because k is zero

Finally function returns x =2 value i.e Number of 1’s in the given input number 5 (101-Binary format).

Other examples:

1 .Still have confusion check for another number k=15 (1111)

The function returns x value 4;

2. Still have confusion check for another number k=10 (1010)

The function returns x value 2;

What does the following function do (i.e. what does the value of x represent at the end)? What does the following function do (i.e. what does the value of x rep

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site