Cho số, tìm số bit 0 dẫn đầu trong biểu diễn nhị phân 32-bit.
Ví dụ: 5 → nhị phân 000...00101 (29 bit 0 dẫn đầu). Code mẫu cho 101 → 25.
Giải thuật
- totalBits = sizeof(n) * 8 (thường 32)
- Chuyển n sang nhị phân string
- Trả về totalBits - độ dài chuỗi nhị phân
Ví dụ minh họa
#include <bits/stdc++.h>
using namespace std;
int getLeadingZeroesCount(unsigned int n) {
int totalBits = sizeof(n) * 8;
string binary = "";
while (n) {
int remainder = n % 2;
if (remainder || binary.length() > 0) binary += remainder;
n /= 2;
}
return totalBits - binary.length();
}
int main() {
int n = 101;
cout << getLeadingZeroesCount(n) << endl;
return 0;
}
Đầu ra
25