0
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?

Pratiksha
  • 3
  • 3
  • 2
    to turn off the rightmost set bit of m just use `m & (m - 1)`. [Off rightmost set bit of an integer](https://stackoverflow.com/q/27540201/995714), [Unset the rightmost set bit (duplicate)](https://stackoverflow.com/a/4703970/995714) – phuclv Sep 22 '20 at 14:55
  • Does this answer your question? [Off rightmost set bit of an integer](https://stackoverflow.com/questions/27540201/off-rightmost-set-bit-of-an-integer) – Enlico Sep 22 '20 at 14:58
  • Does this answer your question? [why bitwise operators require parentheses?](https://stackoverflow.com/questions/42815421/why-bitwise-operators-require-parentheses) – phuclv Sep 22 '20 at 15:07
  • As written, it looks like a homework problem. Normally on Stack Overflow we'd expect you to give an actual example of a bad input, i.e. a value of `n` which should give one outcome but gives another outcome. – MSalters Sep 22 '20 at 15:52

1 Answers1

3

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.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70