problem link:
Discuss: in this problem you just simply convert decimal to binary. then count the number of one's in binary that will be the 'P'. and for converting you can use c++ built in STL string binary = std::bitset<31>(n).to_string(); . and there is no tricky part in this problem.
try yourself, before see the code
#include<bits/stdc++.h>
using namespace std;
void parity(long long n)
{
long long one=0,m,i,flag=0;
string binary = std::bitset<31>(n).to_string();
m=binary.length();
cout <<"The parity of ";
for(i=0;i<m;i++)
{
if(binary[i]=='1')
flag=1;
if(flag)
cout <<binary[i];
}
cout <<" is ";
sort(binary.begin(),binary.end());
for(i=0; i<m; i++)
{
if(binary[i]=='1')
one++;
}
printf("%lld (mod 2).\n",one);
}
int main()
{
long long n,i,j;
while(cin >>n&&n)
{
parity(n);
}
return 0;
}
Discuss: in this problem you just simply convert decimal to binary. then count the number of one's in binary that will be the 'P'. and for converting you can use c++ built in STL string binary = std::bitset<31>(n).to_string(); . and there is no tricky part in this problem.
try yourself, before see the code
#include<bits/stdc++.h>
using namespace std;
void parity(long long n)
{
long long one=0,m,i,flag=0;
string binary = std::bitset<31>(n).to_string();
m=binary.length();
cout <<"The parity of ";
for(i=0;i<m;i++)
{
if(binary[i]=='1')
flag=1;
if(flag)
cout <<binary[i];
}
cout <<" is ";
sort(binary.begin(),binary.end());
for(i=0; i<m; i++)
{
if(binary[i]=='1')
one++;
}
printf("%lld (mod 2).\n",one);
}
int main()
{
long long n,i,j;
while(cin >>n&&n)
{
parity(n);
}
return 0;
}
No comments:
Post a Comment