Home >Backend Development >C++ >C/C++ program: Count the number of digits set in an integer?

C/C++ program: Count the number of digits set in an integer?

王林
王林forward
2023-08-26 18:57:121259browse

C/C++ program: Count the number of digits set in an integer?

Counting set bits means counting 1's for the given integer. For this, we have a variety of solutions that can be applied. For this case, we have a binary number (binary representation of an integer), for which we have to count the number of 1's in the string.

To count the number of 1's, we will get the string, iterate through each element and count the number of all 1's in the string. For example, if we enter 17, the output will be 2 because the binary representation of 17 is 10001, which contains two 1s.

Input: Enter a positive integer: 6
Output: 2

Explanation

The binary representation of 6 is 110, which has 2 set bits

This iteration method requires one iteration for each bit. It runs through all the digits of the number. The iteration terminates when no more bits are set. In the worst case, it will loop for 32 iterations for a 32-bit word with only the most significant bit set. This solution is the simplest solution and is useful if the 1's are sparse and in the least significant bits.

Example

#include <stdio.h>
int main(void) {
   unsigned int n = 34;
   for (c = 0; n; n >>= 1) {
      c += n & 1;
   }
   printf("%d\n", c);
}

The above is the detailed content of C/C++ program: Count the number of digits set in an integer?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete