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

C++Server Side ProgrammingProgramming

Given a number n, we have to find the number of integers with an odd number of set bits in their binary form. Let's see an example.

Input

n = 10

Output

5

There are 5 integers from 1 to 10 with odd number of set bits in their binary form.

Algorithm

  • Initialise the number N.

  • Write a function to count the number of set bits in binary form.
  • 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.

Implementation

Following is the implementation of the above algorithm in C++

#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
raja
Published on 03-Jul-2021 05:25:47

Advertisements