Number of integers with odd number of set bits in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that counts the number of integers with odd number of set bits.

Let's see the steps to solve the problem.

  • Initialise the number N.

  • Initialise the count to 0.

  • Write a loop that iterates from 1 to N.

    • Count the set bits of each integer.

    • Increment the count if the set bits count is odd.

  • Return the count.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getSetBitsCount(int n) {
   int count = 0;
   while (n) {
      if (n % 2 == 1) {
         count += 1;
      }
      n /= 2;
   }
   return count;
}
int getOddSetBitsIntegerCount(int n) {
   int count = 0;
   for (int i = 1; i <= n; i++) {
      if (getSetBitsCount(i) % 2 == 1) {
         count += 1;
      }
   }
   return count;
}
int main() {
   int n = 10;
   cout << getOddSetBitsIntegerCount(n) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

5

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 03-Jul-2021 05:25:47
Advertisements