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
How do you initialize a string in c++?
Please explain class & object in c++?
Can we run c program in turbo c++?
Why was c++ created?
write a corrected statement in c++ so that the statement will work properly. x = y = z + 3a;
What is atoi?
explain the reference variable in c++?
What is time_t c++?
What can I safely assume about the initial values of variables which are not explicitly initialized?
What is an iterator class in c++?
Can member functions be private?
What is the auto keyword good for in c++?
If you hear the cpu fan is running and the monitor power is still on, but you did not see anything show up in the monitor screen. What would you do to find out what is going wrong?
What are the defining traits of an object-oriented language?
Why should you learn c++?