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 |
What is c++ runtime?
Can we declare a base-class destructor as virtual?
can any one help to find a specific string between html tags which is changed to a sting.. weather.html looks (for location) is <location>somewhere</location> #include <iostream> #include <fstream> #include <string> using namespace std; string find_field(string myPage,string); int main (void) { string page, line, location, temperature; ifstream inputFile("weather.xml"); while(getline(inputFile, line)) { page.append(line); line.erase(); } // Now page is a string that contains the whole xml page // Here you need to write something that finds and // extracts location and temperature from the XML // data in the string page and stores them in // the strings location and temperature respectively location=find_field(page,"location"); temperature=find_field(page,"temp_c"); cout << "Location: "<<location << endl; cout << "Temperature: " << temperature << endl; system("pause"); } string find_field(string myPage,string find_string){ int temp=myPage.find(find_string); if(temp!=string::npos) { cout << "Match found at " << temp << endl; } return "found?"; } ///
Can you declare an array without a size in c++?
what is the behaviour of C and C++ compiler for the below statements. int *p; p = malloc(100); Is the behaviour same ? or different ?
What is a constructor initializer list and when we use constructor initializer list?
What are the important differences between c++ and java?
which operator is used for performing an exponential operation a) > b) ^ c) none
how can u create a doubly linked list with out using pointers?
What is the use of endl?
Which is better c++ or java?
What are the difference between reference variables and pointers in C++?