creater number by 1<<(total bits)
3.run a loop and take and with the given number
(i) if(number & with created number in step 2 is zero it means we find left unset bit then take OR of both and break;
(ii) Else Right shift the created number and get in Loop
Why there is TLE.
Edit 1. I know this is long approach but it is what that I think… Please Help
Let me explain this to you using an example. I’ll be considering nybbles of data.
Let us assume k = 1011 and s = 1111 in binary. Notice the bit position 2:
bit positions: 3|2|1|0
1|0|1|1 1|1|1|1 \& \rule{1.5cm}{0.4pt} 1|0|1|1 is != 0
Your code stopped checking here.
But, I added the following to isolate bit position 2:
1|0|1|1 >> 2 = 0|0|1|0
and,
0|0|1|0 0|0|0|1 \& \rule{1.5cm}{0.4pt} 0|0|0|0 is = 0
That’s why we need to shift and then logically and it with 1 for isolating a single bit. Do tell me if you still have anymore doubts.
Then, you may consider s = 0100 to be a valid intermediate value though it starts off with s = 1000, which I didn’t cover as it would give no interesting result and both your and my code would work in that case.