Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Calculate the number of 1's in their binary representation and return them as an array

C++ Math: Exercise-13 with Solution

For a non negative integer in the range 0 ≤ i ≤ n write a C++ programming 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;

vector countBits(int num) {
    	vector res;
        for (int i = 0; i <= num; ++i) {
            res.push_back(0);
        }

        for (int i = 1; i <= num; ++i) {
            res[i] = res[i / 2] + i % 2;
        }

        return res;
    }
    
int main()
{
    int n = 4;
    vector result;
	cout << "Original number: " << n << endl; 
	result = countBits(n);
	for (int x : result) 
        cout << x << " "; 
    n = 7;    
	cout << "\nOriginal number: " << n << endl; 
	result = countBits(n);
	for (int x : result) 
        cout << x << " ";   
    return 0;
}

Sample Output:

Original number: 4
0 1 1 2 1 
Original number: 7
0 1 1 2 1 2 2 3 

Flowchart:

Flowchart: Calculate the number of 1's in their binary representation and return them as an array.

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?