I have to change kth bit from right to 0. If it is already 0 I do not have to change anything.
For n = 37 and k = 3, the output should be 33.
37 = 100101 ~> 100001 = 33
For n = 37 and k = 4, the output should be 37. Since the bit is already 0.
I have seen a couple of answers on SO but, I was not able to figure out.
How to modify bits in an integer?
how to change 1 to 0 and 0 to 1 in binary(Python)
Python – Flipping Binary 1's and 0's in a String
>Solution :
use <<(shift left), & (bitwise and operator) and ~ (bitwise not operator) to achieve this
import sys
def changeBit(val,bit):
flip = 1<<(bit-1)
val = ~(flip) & val
return val
print(changeBit(37,3))