Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements