Give a very good method to count the number of ones in a "n"
(e.g. 32) bit number.
Answers were Sorted based on User's Feedback
Answer / 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 |
Answer / artyom
// It's still O(n), maybe there are better ways.
int countBit(int num)
{
int count = 0;
while(num)
{
count += static_cast<int>(static_cast<bool>(mask &
0x1));
num >>= 1;
}
return count;
}
Is This Answer Correct ? | 2 Yes | 0 No |
Answer / manish kumar
for (c = 0; n; c++)
n &= n - 1;
Result: the value of c.
complexity:o(logn)
Is This Answer Correct ? | 1 Yes | 0 No |
Can we change the basic meaning of an operator in c++?
What c++ is used for?
Difference between pointer to constant and constant pointer to a constant. Give example.
How can we read/write Structures from/to data files?
How do I write a c++ program?
What is function overloading c++?
What C++ libraries are you proficient with?
What is the difference between a declaration and a definition?
What is a list c++?
How does the copy constructor differ from the assignment operator (=)?
You have to take 2 arrays of length 10. Input the values of array 1 from the user. Then copy the values of array 1 to array 2 in ascending order For example if user enters 9, 5, 6, 8, 1, 0, 2, 7, 4, 3 then copy the smallest element i.e. 0 first followed by 1, 2 and so
What is the meaning of string in c++?