Wednesday, February 21, 2024
HomeSoftware EngineeringBit Counting in Golang | Discover ways to Grasp Software program Engineering,...

Bit Counting in Golang | Discover ways to Grasp Software program Engineering, DevOps and Cloud


The problem

Write a operate that takes an integer as enter, and returns the variety of bits which are equal to at least one within the binary illustration of that quantity. You’ll be able to assure that enter is non-negative.

Instance: The binary illustration of 1234 is 10011010010, so the operate ought to return 5 on this case

The answer in Golang

Possibility 1:

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

Possibility 2:

package deal answer
import "math/bits"
var CountBits = bits.OnesCount

Possibility 3:

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

Take a look at circumstances to validate our answer

package deal solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("CountBits()", func() {
  It("fundamental assessments", func() {
    Count on(CountBits(0)).To(Equal(0))
    Count on(CountBits(4)).To(Equal(1))
    Count on(CountBits(7)).To(Equal(3))
    Count on(CountBits(9)).To(Equal(2))
    Count on(CountBits(10)).To(Equal(2))
  })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments