- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
Python program to count unset bits in a range.
Given a positive a number and the range of the bits. Our task is to count unset bits in a range.
Input : n = 50, starting address = 2, ending address = 5 Output : 2
There are '2' unset bits in the range 2 to 5.
Step 1 : convert n into its binary using bin(). Step 2 : remove first two characters. Step 3 : reverse string. Step 4 : count all unset bit '0' starting from index l-1 to r, where r is exclusive.
# Function to count unset bits in a range def countunsetbits(n,st,ed): # convert n into it's binary bi = bin(n) # remove first two characters bi = bi[2:] # reverse string bi = bi[-1::-1] # count all unset bit '0' starting from index l-1 # to r, where r is exclusive print (len([bi[i] for i in range(st-1,ed) if bi[i]=='0'])) # Driver program if __name__ == "__main__": n=int(input("Enter The Positive Number ::>")) st=int(input("Enter Starting Position")) ed=int(input("Enter Ending Position")) countunsetbits(n,st,ed)
Enter The Positive Number ::> 50 Enter Starting Position2 Enter Ending Position5 2
- Related Articles
- Count unset bits in a range in C++
- Count unset bits of a number in C++
- Python Count set bits in a range?
- Count set bits in a range in C++
- Write a python program to count total bits in a number?
- Program to count total number of set bits of all numbers in range 0 to n in Python
- Python Program to Count set bits in an integer
- Program to count operations to remove consecutive identical bits in Python
- Program to count pairs with XOR in a range in Python
- Java program to count total bits in a number
- C# program to count total bits in a number
- C# program to count total set bits in a number
- Python program to count total set bits in all number from 1 to n.
- Program to count odd numbers in an interval range using Python
- Java Program to Count set bits in an integer