BITMEDU5 - Editorial

Problem Link - Count of set bits

Problem Statement -

Write a program that takes an input integer N and prints the count of the set bits present in the number.

Approach -

The code idea is to determine the number of set bits (1s) in the binary representation of the integer N. This is achieved using a loop that continues until N becomes zero. In each iteration, the code checks if the least significant bit (LSB) of N is set (1) by using the expression n % 2. If it is set, it increments the count cnt. Then, the code divides N by 2 to remove the LSB and continues this process until all bits are processed. Finally, the count of set bits is printed.

Time Complexity

O(log N)

Space Complexity

O(1)