def clear_rightmost_set_bit(n):
"""
Clears the rightmost set bit of the given number.
:param n: The input number
:return: The number with the rightmost set bit cleared
"""
return n & (n - 1)
num = int(input("Enter a non-negative integer: "))
result = clear_rightmost_set_bit(num)
print(f"Original number: {num} (Binary: {bin(num)})")
print(f"Number after clearing rightmost set bit: {result} (Binary: {bin(result)})")
#source code --> clcoding.com
Code Explanation:
1. Function Definition
def clear_rightmost_set_bit(n):
"""
Clears the rightmost set bit of the given number.
:param n: The input number
:return: The number with the rightmost set bit cleared
"""
return n & (n - 1)
Key Points:
Rightmost Set Bit:
The rightmost set bit is the first 1 from the right in the binary representation of the number.
For example:
10 (binary: 1010) → The rightmost set bit is the second position from the right (2^1).
18 (binary: 10010) → The rightmost set bit is the fifth position from the right (2^4).
Clearing the Rightmost Set Bit:
The operation n & (n - 1) clears the rightmost set bit. Here's how:
Subtracting 1 from n flips all bits to the right of the rightmost set bit and flips the rightmost set bit to 0.
The & operation (bitwise AND) keeps all other bits unchanged but ensures the rightmost set bit is cleared.
Example:
For n = 10 (binary: 1010):
n - 1 = 9 (binary: 1001)
n & (n - 1) = 1010 & 1001 = 1000 (decimal: 8)
2. Input Handling
num = int(input("Enter a non-negative integer: "))
Prompts the user to input a non-negative integer and stores it in num.
3. Call the Function
result = clear_rightmost_set_bit(num)
Calls the function clear_rightmost_set_bit with the input number num.
Stores the result (the number after clearing the rightmost set bit) in result.
4. Display the Results
print(f"Original number: {num} (Binary: {bin(num)})")
print(f"Number after clearing rightmost set bit: {result} (Binary: {bin(result)})")
bin():
Converts the integer into its binary representation (as a string prefixed with 0b).
For example:
bin(10) → '0b1010'
bin(8) → '0b1000'
Displays:
The original number and its binary representation.
The result after clearing the rightmost set bit and its binary representation.
Output:
Original number: 18 (Binary: 0b10010)
Number after clearing rightmost set bit: 16 (Binary: 0b10000)
Source
0 Comments:
Post a Comment