Write a recursive method in pseudo code that returns the num

Write a recursive method in pseudo code that returns the number of 1\'s in the binary representation of N. Use the fact that this equal to the number of 1\'s in the representation of N/2, plus 1, if N is odd.

Solution

//C++ code

#include <iostream>
using namespace std;

int numOfOnes(int N)
{
// return 0 if N is 0
if (N == 0)
{
return 0;
}
// return 1 if N is one
else if(N == 1)
{
return 1;
}

// else recursively call he function with parameters integer value of (N/2) plus the modulus of N and 2
else
{
return numOfOnes(int(N/2))+numOfOnes(N%2);
}
}

int main()
{
  
int N;
cout << \"Enter number: \";
cin >> N;

cout << \"Number of ones in binary representation of \" << N << \": \" << numOfOnes(N) << endl;

return 0;
}

/*
output:

Enter number: 10
Number of ones in binary representation of 10: 2

Enter number: 15
Number of ones in binary representation of 15: 4

Enter number: 31
Number of ones in binary representation of 31: 5


*/

 Write a recursive method in pseudo code that returns the number of 1\'s in the binary representation of N. Use the fact that this equal to the number of 1\'s i

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site