
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Next higher number with same number of set bits in C++
- Maximum number of contiguous array elements with same number of set bits in C++
- Minimum number using set bits of a given number in C++
- Prime Number of Set Bits in Binary Representation in C++
- Number of pairs with Bitwise OR as Odd number in C++
- Maximum sum by adding numbers with same number of set bits in C++
- Check if a number has same number of set and unset bits in C++
- Sorting Integers by The Number of 1 Bits in Binary in JavaScript
- For every set bit of a number toggle bits of other in C++
- Prime Number of Set Bits in Binary Representation in Python
- Previous smaller integer having one less number of set bits in C++
- Next greater integer having one more number of set bits in C++
- Program to find higher number with same number of set bits as n in Python?\n
- Binary Number with Alternating Bits in C++
- Count unset bits of a number in C++
Advertisements