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

โปรแกรม C/C++ นับจำนวน Set Bits (บิต 1) ในจำนวนเต็ม


นับ Set Bits = นับจำนวน 1 ใน Binary Representation ของ Integer มีหลายวิธี วิธีนี้: แปลงเป็น Binary String วนนับ 1 เช่น 17 -> Binary 10001 มี 1 สองตัว -> Output 2

Input: 6 Output: 2

คำอธิบาย

Binary ของ 6 คือ 110 มี 1 สองตัว

Iterative Approach: วนทีละบิต Shift Right (>>=1) นับ Bit LSB (& 1) จบเมื่อไม่มีบิตเหลือ สูงสุด 32 รอบสำหรับ 32-bit เหมาะกับ 1 น้อยและอยู่ LSB

ตัวอย่าง

#include <stdio.h>
int main(void) {
    unsigned int n = 34;
    int c = 0;
    for (c = 0; n; n >>= 1) {
        c += n & 1;
    }
    printf("%d\n", c);
}