Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Count total bits in a number in C++: นับจำนวน bit ทั้งหมดในการแทนค่า

กำหนดจำนวนเต็ม num หาจำนวน bit ที่ใช้ในการแทนค่า (ไม่รวม leading zeros)

ตัวอย่าง: 50 (110010) → 6 bits, 10 (1010) → 4 bits

วิธีแก้ปัญหา

  • Built-in: 32 - __builtin_clz(num) (สำหรับ 32-bit)
  • Manual: floor(log2(num)) + 1 หรือ shift จนเป็น 0

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

int countTotalBits(unsigned int n) {
    if(n == 0) return 1;
    int count = 0;
    while(n) {
        count++;
        n >>= 1;
    }
    return count;
}

int main() {
    cout << countTotalBits(50) << endl; // 6
    cout << countTotalBits(10) << endl; // 4
}

Input

50

Output

6