diff --git a/DIRECTORY.md b/DIRECTORY.md index 2182471a5f0d..984d36de1422 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -106,6 +106,7 @@ * [Rotate Bits](bit_manipulation/rotate_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) * [Swap All Odd And Even Bits](bit_manipulation/swap_all_odd_and_even_bits.py) + * [Update Bit](bit_manipulation/update_bit.py) ## [Blockchain](blockchain) * [Diophantine Equation](blockchain/diophantine_equation.py) diff --git a/bit_manipulation/update_bit.py b/bit_manipulation/update_bit.py new file mode 100644 index 000000000000..9bd310b18483 --- /dev/null +++ b/bit_manipulation/update_bit.py @@ -0,0 +1,29 @@ +def update_bit(number: int, position: int, value: int) -> int: + """ + It is a program to update a bit at given position + + Details:update the bit at position of the + number by the value provided to it. + and return updated integer. + + >>> update_bit(5,0,0) #0b100 + 4 + >>> update_bit(10,1,0) #0b1000 + 8 + >>> update_bit(15,3,0) #0b0111 + 7 + >>> update_bit(5,1,1) #70b111 + 7 + >>> update_bit(10,0,1) #0b1011 + 11 + """ + + mask = ~(1 << position) + number = number & mask + return number | (value << position) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()