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

ตรวจสอบว่าเลขมีจำนวนบิต 1 และ 0 เท่ากันหรือไม่ ใน C++


ตรวจสอบว่าจำนวนบิต 1 (set bits) และบิต 0 (unset bits) ในการแทนค่าฐานสองเท่ากันหรือไม่

ตัวอย่าง: 12 = 1100₂ มีบิต 1 สองตัว บิต 0 สองตัว → เท่ากัน

วิธี: วนตรวจสอบแต่ละบิต นับ set_count และ unset_count เปรียบเทียบในท้ายที่สุด

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

#include <iostream>
using namespace std;

bool hasSameSetUnset(int n) {
    int set_count = 0, unset_count = 0;
    while(n) {
        if ((n & 1) == 1) set_count++;
        else unset_count++;
        n = n >> 1;
    }
    return (set_count == unset_count);
}

int main() {
    int num = 35; // 100011
    if (hasSameSetUnset(num)) cout << "Has same set, unset bits";
    else cout << "Not same number of set, unset bits";
}

ผลลัพธ์

Has same set, unset bits