fork download
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func hitungNomorBit(angka int, nomorBit int) interface{} {
  6. if nomorBit != 0 && nomorBit != 1 {
  7. return nil
  8. }
  9.  
  10. if angka == 0 {
  11. if nomorBit == 0 {
  12. return 1
  13. }
  14. return 0
  15. }
  16.  
  17. count := 0
  18. temp := angka
  19.  
  20. for temp > 0 {
  21. bit := temp % 2
  22. if bit == nomorBit {
  23. count++
  24. }
  25. temp = temp / 2
  26. }
  27.  
  28. return count
  29. }
  30.  
  31. func main() {
  32. fmt.Println("hitungNomorBit(13, 0):", hitungNomorBit(13, 0))
  33. fmt.Println("hitungNomorBit(13, 1):", hitungNomorBit(13, 1))
  34. fmt.Println("hitungNomorBit(13, 2):", hitungNomorBit(13, 2))
  35.  
  36. fmt.Println("\nTesting dengan angka lain:")
  37. fmt.Println("hitungNomorBit(7, 0):", hitungNomorBit(7, 0))
  38. fmt.Println("hitungNomorBit(7, 1):", hitungNomorBit(7, 1))
  39. fmt.Println("hitungNomorBit(8, 0):", hitungNomorBit(8, 0))
  40. fmt.Println("hitungNomorBit(8, 1):", hitungNomorBit(8, 1))
  41. fmt.Println("hitungNomorBit(0, 0):", hitungNomorBit(0, 0))
  42. fmt.Println("hitungNomorBit(0, 1):", hitungNomorBit(0, 1))
  43. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
hitungNomorBit(13, 0): 1
hitungNomorBit(13, 1): 3
hitungNomorBit(13, 2): <nil>

Testing dengan angka lain:
hitungNomorBit(7, 0): 0
hitungNomorBit(7, 1): 3
hitungNomorBit(8, 0): 3
hitungNomorBit(8, 1): 1
hitungNomorBit(0, 0): 1
hitungNomorBit(0, 1): 0