Given a number n, count number of integers smaller than or equal to n that have odd number of set bits.
Input : 5 Output : 3 Explanation : Integers with odd number of set bits in range 1 to 5 : 0 contains 0 set bits 1 contains 1 set bits 2 contains 1 set bits 3 contains 2 set bits 4 contains 1 set bits 5 contains 2 set bits Input : 10 Output : 5 Explanation : Integers with odd set bits are 1, 2, 4, 7 and 8.
Prerequisites : Count number of set bits
The idea is based on below fact.
If n is odd then there are total n+1 integers smaller than or equal to n (0, 1, 2 … n) and half of these integers contain odd number of set bits.
How to handle case when n is even? We know result for n-1. We count set bits in n and add 1 to n/2 if the count is odd. Else we return n/2.
// CPP code to find numbers with
// odd number of set bits
using namespace std;
// function that returns the number
// of integers with odd number of
// set bits
int countWithOddSetBits(int n)
// If n is odd, then half of the
// integers in (0, 1, .. n) contain
// odd number of set bits.
if (n % 2 != 0)
return (n + 1) / 2;
// If n is even, we know result for
// n-1. We explicitly compute set bit
// count in n.
int count = __builtin_popcount(n);
int ans = n / 2;
if (count % 2 != 0)
// Driver code
int n = 10;
cout << countWithOddSetBits(n);
- Number with set bits only between L-th and R-th index
- Check whether the number has only first and last bits set | Set 2
- Maximum sum by adding numbers with same number of set bits
- Program to invert bits of a number Efficiently
- DFA in LEX code which accepts even number of zeros and even number of ones
- Find the missing element in an array of integers represented in binary format
- Prime number in PL/SQL
- Program for nth Catalan Number
- Check if a number is Palindrome in PL/SQL
- log() function for complex number in C++
- Count pairs with Bitwise AND as ODD number
- Lex Program to count number of words
- Check if a number N starts with 1 in b-base
- Find if given number is sum of first n natural numbers
- Find number of days between two given dates
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : jit_t