The problem
Write a operate that takes an integer as enter, and returns the variety of bits which can be 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
Choice 1:
package deal answer
import "math/bits"
func CountBits(n uint) int {
return bits.OnesCount(n)
}
Choice 2:
package deal answer
import "math/bits"
var CountBits = bits.OnesCount
Choice 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 instances to validate our answer
package deal solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("CountBits()", func() {
It("primary exams", 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))
})
})