- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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.
- Related Articles
- Python Program to Count set bits in an integer
- Java Program to Count set bits in an integer
- C/C++ Program to the Count set bits in an integer?
- C/C++ Program to Count set bits in an integer?
- Count set bits in an integer in C++
- Shift the bits of an integer to the left and set the count of shifts as an array in Numpy
- Shift the bits of an integer to the right and set the count of shifts as an array with signed integer type in Numpy
- C# program to count total set bits in a number
- Sort an array according to count of set bits in C++
- Golang Program to Find the Smallest Divisor of an Integer
- Golang Program to Generate all the Divisors of an Integer
- Golang Program To Get The Successor Of An Integer Number
- Python Count set bits in a range?
- Python program to count total set bits in all number from 1 to n.
- Golang Program to convert an integer into binary representation

Advertisements