Home > Backend Development > C++ > body text

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

王林
Release: 2023-08-26 18:57:12
forward
1224 people have browsed it

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
Copy after login

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);
}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!