Set Bits

Easy
0/40
profile
Contributed by
284 upvotes
Asked in companies
AmazonD.E.ShawGoogle inc

Problem statement

Write a program to count the number of 1's in the binary representation of an integer.

Detailed explanation ( Input/output format, Notes, Images )
Input format :
 The only line of input contains a single integer N.
Output format :
The only line of the output prints the total number of 1.
Constraints
1 <= N <= 100
Sample Input 1:
9
Sample Output 1:
2
Explanation of Sample Input 1:
Binary Representation of 9 is 1001.
Sample Input 2:
13
Sample Output 2:
3
Hint

Iterate through all bits

Approaches (1)
Looping through bits Approach
  • Here we are converting the number into binary, and during the conversion, we are checking the remainder part.
  • If it is 1, then we increment the value of count by 1.
Time Complexity

O(log(N)), where ‘N’ is the given integer.

Since we are iterating through each bit of binary representation of the given number which is O(log(N)) in size. So the overall time complexity will be O(log(N)).

Space Complexity

O(1)

 

We are using constant extra space.

Code Solution
(100% EXP penalty)
Set Bits
Full screen
Console