C++ Exercises: Calculate the number of 1's in their binary representation and return them as an array
For a non negative integer in the range 0 ≤ i ≤ n write a C++ program to calculate the number of 1's in their binary representation and return them as an array.
Input: 9
Output: true
Input: 81
Output: true
Input: 45
Output: false
Sample Solution:
C++ Code :
#include <iostream>
#include <vector>
using namespace std;
// Function to count bits for numbers from 0 to num
vector<int> countBits(int num) {
// Vector to store the counts of bits for numbers from 0 to num
vector<int> res;
// Initializing the vector with 0 for numbers from 0 to num
for (int i = 0; i <= num; ++i) {
res.push_back(0);
}
// Calculating the count of bits for each number from 1 to num
for (int i = 1; i <= num; ++i) {
// The count of bits for a number 'i' is the count of bits for i/2 plus the last bit of 'i'
res[i] = res[i / 2] + i % 2;
}
return res; // Return the vector containing the count of bits for each number
}
int main() {
int n = 4;
vector<int> result;
cout << "Original number: " << n << endl;
result = countBits(n); // Calculate count of bits for numbers from 0 to n
for (int x : result)
cout << x << " "; // Display the count of bits for each number from 0 to n
n = 7;
cout << "\nOriginal number: " << n << endl;
result = countBits(n); // Calculate count of bits for numbers from 0 to n
for (int x : result)
cout << x << " "; // Display the count of bits for each number from 0 to n
return 0;
}
Sample Output:
Original number: 4 0 1 1 2 1 Original number: 7 0 1 1 2 1 2 2 3
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ programming to check if a given integer is a power of three or not.
Next: Write a C++ programming to get the maximum product from a given integer after breaking the integer into the sum of at least two positive integers.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics