Golang Program to count the set bits in an integer.

Go ProgrammingServer Side ProgrammingProgramming

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.
raja
Published on 17-Mar-2021 11:35:17
Advertisements