একটি সংখ্যা এবং একটি বিট রেঞ্জ (left, right) দেওয়া থাকলে, সেই রেঞ্জে কতটি আনসেট বিট (০) আছে তা গণনা করতে হবে। বিট পজিশন ১-বেসড (LSB = ১)।
উদাহরণ
সংখ্যা: 50 (বাইনারি: 00110010)
রেঞ্জ: left=2, right=5
বিট পজিশন ২ থেকে ৫: 1, 0, 0, 1 → আনসেট বিট = 2টি
অ্যালগরিদম
- রেঞ্জের মোট বিট = right - left + 1
- সেট বিট গণনা করতে বিটমাস্ক ব্যবহার করুন:
- মাস্ক =
((1 << right) - 1) ^ ((1 << (left-1)) - 1) - সেট বিট =
__builtin_popcount(n & mask)
- মাস্ক =
- আনসেট বিট = মোট বিট - সেট বিট
C++ কোড উদাহরণ
#include <iostream>
using namespace std;
void countUnsetBitsInRange(unsigned int n, unsigned int left, unsigned int right) {
cout << "8-bit binary of " << n << " is: ";
for (int i = 7; i >= 0; i--)
cout << ((n >> i) & 1);
cout << endl;
int totalBits = right - left + 1;
// Create mask for range [left, right] (1-indexed from LSB)
int mask = ((1 << right) - 1) ^ ((1 << (left - 1)) - 1);
int setBits = __builtin_popcount(n & mask);
int unsetBits = totalBits - setBits;
cout << "Unset bits in range [" << left << "," << right << "]: " << unsetBits;
}
int main() {
unsigned int n = 80, left = 1, right = 4;
countUnsetBitsInRange(n, left, right);
return 0;
}
ইনপুট
80, left=1, right=4
আউটপুট
8-bit binary of 80 is: 01010000 Unset bits in range [1,4]: 2