![]() |
In binary representation of a number, a set bit is defined as the binary digit (bit) that is set to 1. In this article, we will learn how to count the set bits in a given integer in C++. Example Input: 13 Counting Set Bits in an IntegerTo count the set bits in a number in C++, we can directly use the __builtin_popcount() method provided by the GCC compiler in C++. This function returns the number of set bits in a given unsigned integer. Syntax__builtin_popcount(int x); Here, x is the unsigned or positive number for which you want to determine the number of set bits. C++ Program to Count Number of Set Bits in an IntegerThe following program illustrates how we can count the set bits of a number using the __builtin_popcount() method in C++.
Output Number of set bits in 5 (101) is: 2 Number of set bits in 13 (1101) is: 3 Time Complexity: O(1) To learn about other methods for counting set bits in an integer you may refer to this article : Counting Set Bits in an integer |
Reffered: https://www.geeksforgeeks.org
C++ |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 20 |