- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of integers with odd number of set bits in C++
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
Advertisements