I was coding and the following code doesn't give the desired output. pos&1 is supposed to return the remainder when pos is divided by 2. When I replace pos&1 by pos%2 everything works just fine. What could be the problem?
#include <iostream>
using namespace std;
int main(){
int y;
unsigned long long int pos;
cin>>y;
cin>>pos;
int f=0;
while(y>0){
y--;
if(pos&1==0){
f=1-f;
}
pos=pos/2;
}
if(f==1){
cout<<"blue\n";
}
else
cout<<"red\n";
return 0;
}
pos & 1
rather thanpos % 2
? Obfuscation?cin
andcout
were not declared). After adding the missing#include <iostream>
and using-directive (or using-declarations), compiling withg++ -Wall
I getwarning: suggest parentheses around comparison in operand of ‘&’ [-Wparentheses]
, which hints thatpos&1==0
really meanspos & (1==0)
(while you want(pos&1) == 0
). Always compile with warnings. (I suggest-Wextra -Wconversion
in addition to-Wall
, and-pedantic-errors
with-std=c++98
/-std=c++11
.) Also yourcout<<"red\n";
is not indented.pos & 1
, but you obfuscated the issue with your==
and all of the surrounding code. Hopefully your debugging method in future will include creating a testcase, and then you won't even have to ask for help. :-) Divide and conquer, my friend.