Was it helpful?

Question

Program to find number of bit 1 in the given number in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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
raja
Published on 06-Oct-2020 10:20:05
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top