Reputation: 3
I'm a newbie to c++. I attempted a questions related to bitsets(https://www.codechef.com/problems/CHEFQUE), when I use the following nested statements the code passes all the tests
for(int i=1;i<Q+1;i++){
temp = S/2;
if(S&1){ //odd
if(!sets[temp]){
sets[temp] = true;
sum+=temp;
}
}
else{ //even
if(sets[temp]){
sets[temp] = false;
sum-=temp;
}
}
S = (A*S + B);
But when I combine the multiple if-else statements, it fails on some tests
for(int i=1;i<Q+1;i++){
temp = S/2;
if(S&1 && !sets[temp]){ //odd and empty
sets[temp] = true;
sum+=temp;
}
else if(!S&1 && sets[temp]){ //even ond occupied
sets[temp] = false;
sum-=temp;
}
S = (A*S + B);
}
I really have no clue why this would happen, I'm sure it must be really stupid. I would really be thankful if someone helped.
Upvotes: 0
Views: 71
Reputation: 12909
As you can see from this table the operator !
has a higher precedence that &
(Bitwise and, not address of), so your code should looks like this:
for(int i=1;i<Q+1;i++){
temp = S/2;
if(S&1 && !sets[temp]){ //odd and empty
sets[temp] = true;
sum+=temp;
}
else if(!(S&1) && sets[temp]){ //even ond occupied
sets[temp] = false;
sum-=temp;
}
S = (A*S + B);
}
Upvotes: 1