Bit Counting in Golang

0 min read 152 words

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))
  })
})
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts