def count_set_bits(n):
count=0
while n > 0:
count += n & 1
n >>= 1
return count
num=int(input("Enter an integer"))
print(f"The number of set bits in {num}is{count_set_bits(num)}.")
#source code --> clcoding.com
Code Explanation:
Function: count_set_bits
def count_set_bits(n):
count = 0
while n > 0:
count += n & 1
n >>= 1
return count
Initialization:
count = 0: Initializes a variable count to store the number of set bits.
Logic:
n & 1: This operation checks if the least significant bit (LSB) of n is 1.
& is a bitwise AND operator. It returns 1 only if both corresponding bits are 1.
For example:
5 (binary: 101) & 1 (binary: 001) = 1 (LSB is 1).
4 (binary: 100) & 1 (binary: 001) = 0 (LSB is 0).
count += n & 1: Adds 1 to count if the LSB of n is 1.
n >>= 1: Right-shifts n by 1 bit to examine the next bit.
For example:
If n = 5 (binary: 101), n >> 1 = 2 (binary: 10).
If n = 2 (binary: 10), n >> 1 = 1 (binary: 1).
Loop Condition:
The loop continues as long as n > 0, meaning there are more bits to check.
Return Value:
The function returns count, which is the total number of set bits in the binary representation of n.
num = int(input("Enter an integer"))
Prompts the user to input an integer (num).
Converts the input string to an integer using int().
print(f"The number of set bits in {num} is {count_set_bits(num)}.")
Calls the count_set_bits function with num as input.
Prints the number of set bits.
Input:
Enter an integer: 5
Execution of count_set_bits(5)
Initial value: n = 5 (binary: 101), count = 0.
First iteration:
n & 1: 101 & 001 = 1 (LSB is 1).
count += 1: count = 1.
n >>= 1: n = 2 (binary: 10).
Second iteration:
n & 1: 10 & 01 = 0 (LSB is 0).
count = 1 (no increment).
n >>= 1: n = 1 (binary: 1).
Third iteration:
n & 1: 1 & 1 = 1 (LSB is 1).
count += 1: count = 2.
n >>= 1: n = 0 (loop exits).
Return count = 2.
Output:
The number of set bits in 5 is 2.
0 Comments:
Post a Comment