Give a very good method to count the number of ones in a "n"
(e.g. 32) bit number.
Answer Posted / sujan
#include<iostream>
#define bit 32
using namespace std;
int array[bit];
int bitConvert(int n)
{
int a,j=0;
a=n%2;
for(int i=bit;i>=0;i--)
{
n=n/2;
array[i]=a;
a=n%2;
}
for(int i=0;i<=bit;i++)
{
cout<<array[i];
}
}
int countBit(int a[])
{
int *ptr;
ptr=a;
int j=0;
for(int i=0;i<=bit;i++)
{
if(*ptr==1)
{
j++;
}
ptr++;
}
cout<< j;
}
int main()
{
int n;
cout<<"Enter the no:";
cin>>n;
cout<<"\n"<<"BitConversion of "<<n<< "is:";
bitConvert(n);
cout<<endl<<endl;
cout<<"\n"<<"No. of bit:";
countBit(array);
system("pause");
}
| Is This Answer Correct ? | 4 Yes | 1 No |
Post New Answer View All Answers
What is c++ course?
What is setbase c++?
What is the use of map in c++?
What is the c++ programming language used for?
What is lambda in c++?
what are the types of Member Functions?
How are the features of c++ different from c?
What is the best way to declare and define global variables?
what are Operators and explain with an example?
what is pre-processor in C++?
What are the methods of exporting a function from a dll?
What is a linked list in c++?
How is data hiding achieved in c++?
Can a program run without main?
What's the order in which the objects in an array are destructed?