Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Golang Program to count the set bits in an integer.



Examples

For example, 101, 11, 11011 and 1001001 set bits count 2, 2, 4 and 3 respectively.

Approach to solve this problem

Step 1 − Convert number into binary representation.

Step 2 − Count the number of 1s; return count.

Example

 Live Demo

package main
import (
   "fmt"
   "strconv"
)
func NumOfSetBits(n int) int{
   count := 0
   for n !=0{
      count += n &1
      n >>= 1
   }
   return count
}
func main(){
   n := 20
   fmt.Printf("Binary representation of %d is: %s.\n", n,
   strconv.FormatInt(int64(n), 2))
   fmt.Printf("The total number of set bits in %d is %d.\n", n, NumOfSetBits(n))
}

Output

Binary representation of 20 is: 10100.
The total number of set bits in 20 is 2.
Updated on: 2021-03-17T11:38:50+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements