
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Clear the Rightmost Set Bit of a Number in Python
When it is required to clear the rightmost bit of a number which was previously set, the ‘&’ operator can be used.
Below is the demonstration of the same −
Example
def clear_right_bit(my_val): return my_val & (my_val-1) n_val = 6 print("The vlaue of n is :") print(n_val) print("The number after unsetting the rightmost set bit is ") print(clear_right_bit(n_val))
Output
The vlaue of n is : 6 The number after unsetting the rightmost set bit is 4
Explanation
A method is defined that takes an integer as a parameter.
It computes the ‘&’ operation between the number and the number decremented by 1.
Outside the method, an integer is defined, and the method is called by passing the parameter.
The output is displayed on the console.
Advertisements