
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the Number of 1 Bits in a large Binary Number in C++
Given a 32-bit Unsigned Binary Number, the task is to count the set bits, i.e., '1's present in it.
For Example
Input:
N = 00000000000000100111
Output:
4
Explanation: Total set bits present in the given unsigned number is 4, thus we will return the output as '4'.
Approach to Solve this Problem
We have given an unsigned 32-bit binary number. The task is to count how many '1's present in it.
To count the number of '1's present in the given binary number, we can use the inbuilt STL function '__builin_popcount(n)' which takes a binary number as the input parameter.
- Take a binary number N as the input.
- A function count1Bit(uint32_t n) takes a 32-bit binary number as the input and returns the count of '1' present in the binary number.
- The inbuilt function __builtin_popcount(n) takes the input of 'n' as a parameter and returns the count.
Example
#include<bits/stdc++.h> using namespace std; int count1bits(uint32_t n) { return bitset < 32 > (n).count(); } int main() { uint32_t N = 0000000010100000011; cout << count1bits(N) << endl; return 0; }
Running the above code will generate the output as,
Output
4
In the given number, there are 4 set bits or '1s' present in it. So, the output is '4'.
- Related Articles
- Sorting Integers by The Number of 1 Bits in Binary in JavaScript
- Number of 1 Bits in Python
- Binary Number with Alternating Bits in C++
- Prime Number of Set Bits in Binary Representation in C++
- Prime Number of Set Bits in Binary Representation in Python
- Print the number of set bits in each node of a Binary Tree in C++ Programming.
- Minimum number using set bits of a given number in C++
- Count unset bits of a number in C++
- Program to find longest consecutive run of 1 in binary form of a number in C++
- Check if a number has bits in alternate pattern - Set 1 in C++
- Draw a Turing machine to find 1’s complement of a binary number
- Reversing the bits of a decimal number and returning new decimal number in JavaScript
- Factorial of a large number
- Find row number of a binary matrix having maximum number of 1s in C++
- Python program to find factorial of a large number

Advertisements