I have solved two questions in bitmasking i.e unique number2 and playing with bits. I use Xcode to code.
According to me I have programmed them correctly, but I am getting run error while submitting the code.
I am not able to figure out my error.
Code for unique number2
#include
using namespace std;
int setbits(int m,int n){
int temp=m;int i=0;int ans=0; int a[10];
while(m<=n){
a[i]=m;
m++;
i++;
}
m=temp;
for(i=0;i<=(n-m);i++){
while(a[i]>0){
if((a[i]&1)==1){
ans++;
}
a[i]=a[i]>>1;
}
}
return ans;
}
int main(){
int a[10];int m,n;int i=0;int q;
cin>>q;
for(i=0;i<q;i++){
cin>>m;
cin>>n;
a[i]=setbits(m,n);
}
for(i=0;i<q;i++){
cout<<a[i]<<endl;
}
return 0;
}
code for playing with bits:
#include
using namespace std;
int setbits(int m,int n){
int temp=m;int i=0;int ans=0; int a[10];
while(m<=n){
a[i]=m;
m++;
i++;
}
m=temp;
for(i=0;i<=(n-m);i++){
while(a[i]>0){
if((a[i]&1)==1){
ans++;
}
a[i]=a[i]>>1;
}
}
return ans;
}
int main(){
int a[10];int m,n;int i=0;int q;
cin>>q;
for(i=0;i<q;i++){
cin>>m;
cin>>n;
a[i]=setbits(m,n);
}
for(i=0;i<q;i++){
cout<<a[i]<<endl;
}
return 0;
}