Search code examples
c++bit

Turn off the rightmost set bit


int n;
        cin>>n;
        int i=1,m=1;
        while(n&i==0)
        {
            i=i<<1;
            m++;
            
        }
        //now flip mth set bit from right;
        int ans=n^(1<<(m-1));
        cout<<ans<<endl;

What is the mistake in the above code for unsetting the rightmost bit of an integer?


Solution

  • In C++ == operator has higher precedence than & operator, so n&i==0 won't be what you want. Use (n&i)==0 instead of that.