public class Main
{
public static void main
(String[] args
) { System.
out.
println(hitungNomorBit
(13,
0)); System.
out.
println(hitungNomorBit
(13,
1)); System.
out.
println(hitungNomorBit
(13,
2)); }
public static Integer hitungNomorBit
(int angka,
int nomorBit
) { int zero_counter = 0;
int one_counter = 0;
int temp = 0;
while(angka > 0) {
temp = angka % 2;
if(temp == 0) {
zero_counter++;
} else if (temp == 1) {
one_counter++;
}
angka = angka / 2;
}
// Angka biner tidak perlu ditampilkan maka langsung ke penghitungan nomorBit.
if(nomorBit == 0) {
return zero_counter;
} else if(nomorBit == 1) {
return one_counter;
}
return null;
}
}
cHVibGljIGNsYXNzIE1haW4KewoJcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewogICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbihoaXR1bmdOb21vckJpdCgxMywgMCkpOwogICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbihoaXR1bmdOb21vckJpdCgxMywgMSkpOwogICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbihoaXR1bmdOb21vckJpdCgxMywgMikpOwoJfQoJCglwdWJsaWMgc3RhdGljIEludGVnZXIgaGl0dW5nTm9tb3JCaXQoaW50IGFuZ2thLCBpbnQgbm9tb3JCaXQpIHsKICAgICAgICBpbnQgemVyb19jb3VudGVyID0gMDsKICAgICAgICBpbnQgb25lX2NvdW50ZXIgPSAwOwogICAgICAgIGludCB0ZW1wID0gMDsKICAgICAgICAKICAgICAgICB3aGlsZShhbmdrYSA+IDApIHsKICAgICAgICAgICAgdGVtcCA9IGFuZ2thICUgMjsKICAgICAgICAgICAgCiAgICAgICAgICAgIGlmKHRlbXAgPT0gMCkgewogICAgICAgICAgICAgICAgemVyb19jb3VudGVyKys7CiAgICAgICAgICAgIH0gZWxzZSBpZiAodGVtcCA9PSAxKSB7CiAgICAgICAgICAgICAgICBvbmVfY291bnRlcisrOwogICAgICAgICAgICB9CiAgICAgICAgICAgIAogICAgICAgICAgICBhbmdrYSA9IGFuZ2thIC8gMjsKICAgICAgICB9CiAgICAgICAgCiAgICAgICAgLy8gQW5na2EgYmluZXIgdGlkYWsgcGVybHUgZGl0YW1waWxrYW4gbWFrYSBsYW5nc3VuZyBrZSBwZW5naGl0dW5nYW4gbm9tb3JCaXQuIAogICAgICAgICAgICAKICAgICAgICBpZihub21vckJpdCA9PSAwKSB7CiAgICAgICAgICAgIHJldHVybiB6ZXJvX2NvdW50ZXI7CiAgICAgICAgfSBlbHNlIGlmKG5vbW9yQml0ID09IDEpIHsKICAgICAgICAgICAgcmV0dXJuIG9uZV9jb3VudGVyOwogICAgICAgIH0KICAgICAgICByZXR1cm4gbnVsbDsKCX0gICAKfQo=