Help me with this simple problem

Converting a binary number to linkedlist
in this problem the code looks like this:

in the bit manipulation we declare res=0
in the loop we first shift res by 1 towards the left why? first we must add the current value then shift by one right?

int res=0;
while(head){
 res=res<<1; //why do we increment here
 res=res| head->value;
 head=head->next;
 //and not here res=res<<1
 }

Perhaps I’m misunderstanding something, but after reading the problem statement, it looks like it’s doing the opposite i.e. converting a linked list to a number.

Edit:

Oh, I see; your confusion is this bit:

No: consider what happened if the linked list consisted of a single node with the binary digit “1”: the correct result is 1, but “add the current value then shift by one” would result in 2.

2 Likes