Bit Counting in Golang


The challenge

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case

The solution in Golang

Option 1:

package solution
import "math/bits"
func CountBits(n uint) int {
  return bits.OnesCount(n)
}

Option 2:

package solution
import "math/bits"
var CountBits = bits.OnesCount

Option 3:

package solution
func CountBits(n uint) int {
  var res int = 0
  for (n>0) {
    if (n & 1 == 1) {
      res = res + 1
    }
    n = n >> 1
  }
  return res
}

Test cases to validate our solution

package solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("CountBits()", func() {
  It("basic tests", func() {
    Expect(CountBits(0)).To(Equal(0))
    Expect(CountBits(4)).To(Equal(1))
    Expect(CountBits(7)).To(Equal(3))
    Expect(CountBits(9)).To(Equal(2))
    Expect(CountBits(10)).To(Equal(2))
  })
})