
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Clear Bit Ranges in Given Number in C++
Given a number n, write C++ program to clear bits in the given range between l and r. Where, 1 <= l <= r <= number of bits in the binary representation of n.
Approaches to clear bits in the given range
Following are the different approaches to clear bit ranges in given number in C++ ?
Using Brute Force Approach
Following are the steps to clear bit ranges in given number using Brute force approach ?
-
Step 1: Create a function to clear the i-th bit named clearIthBit().
- Create a mask with 0 at the i-th position and 1s everywhere else.
- Apply the mask to n using bitwise AND to clear the i-th bit.
- Step 2: Use a loop to clear each bit from index l to r individually and call the function clearIthBit().
Example
#include <iostream> using namespace std; int clearIthBit(int n, int i) { int mask = ~(1 << i); return n & mask; } int main() { int n = 63; int l = 1, r = 3; int result = 0; for (int i = l - 1; i < r; i++) { n = clearIthBit(n, i); } cout << n; return 0; }
Space Complexity: O(1)
Time Complexity: O(r-l+1)
Since we are running a loop from l to r.
Using Optimized Approach
Following are the steps to clear bit ranges in a given number using Optimized Approach?
- Step 1: Create a mask with all bits set to 1. This can be done by taking bitwise NOT(~) of 0. Since 0 can be 000....0000, its negation will be 111....1111.
- Step 2: Create a mask for all the right side bits i.e. we need to shift all 1's r times.
- Step 3: Create a mask for all left side bits i.e. we need to keep all bits 1 (l-1) times.
- Step 4: Combine masks to get a mask with 0s from l to r and 1s elsewhere.
- Step 5: Clear the bits from l to r in n using the mask.
Example
#include <iostream> using namespace std; int clearBits(int n, int l, int r) { int allOnes = ~0; int leftMask = allOnes << (r); int rightMask = (1 << (l-1)) - 1; int mask = leftMask | rightMask; return n & mask; } int main() { int n, l, r; cout << "Enter the number (n): "; cin >> n; cout << "Enter the left index (l): "; cin >> l; cout << "Enter the right index (r): "; cin >> r; int result = clearBits(n, l, r); cout << "Result after clearing bits from " << l << " to " << r << " is: " << result << endl; return 0; }
Space Complexity: O(1)
Time Complexity: O(1)
Advertisements