- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find number of bit 1 in the given number in Python
Suppose we have a number n, we have to find the number of bit 1 present in the binary representation of that number.
So, if the input is like 12, then the output will be 2
To solve this, we will follow these steps −
- count := 0
- while n is non-zero, do
- count := count + (n AND 1)
- n := floor of (n / 2)
- return count
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n): count = 0 while (n): count += n & 1 n >>= 1 return count ob = Solution() print(ob.solve(12))
Input
12
Output
2
Advertisements