0

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;
}
4
  • 2
    @Why do you want to write pos & 1 rather than pos % 2? Obfuscation? Commented Oct 28, 2013 at 9:40
  • Note: The original code doesn't compile (cin and cout were not declared). After adding the missing #include <iostream> and using-directive (or using-declarations), compiling with g++ -Wall I get warning: suggest parentheses around comparison in operand of ‘&’ [-Wparentheses], which hints that pos&1==0 really means pos & (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 your cout<<"red\n"; is not indented.
    – gx_
    Commented Oct 28, 2013 at 10:25
  • 1
    This is what happens when you don't reduce your problem to a testcase. You could trivially have confirmed the value of 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. Commented Oct 28, 2013 at 11:13
  • thanks will take care in future.Help appreciated, everyone! :)@james % has logn complexity while & is maddeningly fast when it has to be used several times.Thats the reason i have used it over here.
    – user103260
    Commented Oct 28, 2013 at 11:30

1 Answer 1

12

1==0 takes more precedence than pos&1. Try if((pos&1)==0){

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.