return n & ~(1 << (k-1))
do what you're looking for.
I recommend that you reread the problem statement; in this type of operations, for k
it is usually considered that its first value is 0, so that (k-1)
would simply remain as k
(and the result for (n, k) = (37, 3) would not be 33, but 37). Indeed, with pencil and paper it is easier to understand.
The operators <<
and >>
move a value to the left or right (multiply or divide by 2). In this case we start with a 1 and move it to the left k-1
bits. We already have 1 above the bit of n
that we want to modify.
Since what we want to do is set the bit to 0, we use ~
to deny the 1, putting it to 0 and the rest of the bits to 1. Then, when doing &
with n
we will leave < em> pass the bits that correspond to the 1 in our mask, leaving 0 to those that do not.
For you to hit a review, this (although something more convoluted) would give the same result:
return ~(~n | (1 << (k-1)))
. Do you understand why?