
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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++
- Program to find higher number with same number of set bits as n in Python?\n
- Sorting Integers by The Number of 1 Bits in Binary in JavaScript
- Maximum sum by adding numbers with same number of set bits in C++
- Prime Number of Set Bits in Binary Representation in C++
- Prime Number of Set Bits in Binary Representation in Python
- Check if a number has same number of set and unset bits in C++
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Check if all bits of a number are set in Python
- Number of pairs with Bitwise OR as Odd number in C++
- For every set bit of a number toggle bits of other in C++
- Previous smaller integer having one less number of set bits in C++
- Next greater integer having one more number of set bits in C++

Advertisements