#include <stdio.h>
int hitungNomorBit(int angka, int nomorBit) {
// Jika angka negatif atau nomorBit negatif, kembalikan -1 (null)
if (angka < 0 || nomorBit < 0) {
return -1;
}
int count = 0; // Menghitung jumlah bit 1
int temp = angka;
int bitPosition = 0;
// Iterasi hingga nomorBit atau hingga angka menjadi 0
while (temp > 0 && bitPosition <= nomorBit) {
// Periksa bit paling kanan menggunakan AND dengan 1
if (temp & 1) {
count++;
}
// Geser ke kanan untuk memeriksa bit berikutnya
temp = temp >> 1;
bitPosition++;
}
// Jika nomorBit lebih besar dari jumlah bit dalam angka, kembalikan -1
if (nomorBit >= bitPosition && temp == 0) {
return -1;
}
return count;
}
int main() {
// Contoh pengujian
printf("%d\n", hitungNomorBit
(13, 0)); // Harusnya akan menghasilkan output: 1 printf("%d\n", hitungNomorBit
(13, 1)); // Harusnya akan menghasilkan output: 2 printf("%d\n", hitungNomorBit
(13, 2)); // Harusnya akan menghasilkan output: 3 printf("%d\n", hitungNomorBit
(13, 3)); // Harusnya akan menghasilkan output: 4 printf("%d\n", hitungNomorBit
(13, 4)); // Harusnya akan menghasilkan output: -1 (null) return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CgppbnQgaGl0dW5nTm9tb3JCaXQoaW50IGFuZ2thLCBpbnQgbm9tb3JCaXQpIHsKICAgIC8vIEppa2EgYW5na2EgbmVnYXRpZiBhdGF1IG5vbW9yQml0IG5lZ2F0aWYsIGtlbWJhbGlrYW4gLTEgKG51bGwpCiAgICBpZiAoYW5na2EgPCAwIHx8IG5vbW9yQml0IDwgMCkgewogICAgICAgIHJldHVybiAtMTsKICAgIH0KICAgIAogICAgaW50IGNvdW50ID0gMDsgLy8gTWVuZ2hpdHVuZyBqdW1sYWggYml0IDEKICAgIGludCB0ZW1wID0gYW5na2E7CiAgICBpbnQgYml0UG9zaXRpb24gPSAwOwogICAgCiAgICAvLyBJdGVyYXNpIGhpbmdnYSBub21vckJpdCBhdGF1IGhpbmdnYSBhbmdrYSBtZW5qYWR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