0

input is a binary string (32 bit) - n we have to reverse the binary string and print that number.

we can come up with code like this

        rev = 0
        for i in range(0,32):
            rev = (rev<<1) + (n & 1)
            n = n>>1
        return rev

just wanted to know if we can use the "or" operator instead of "and" something like

rev = (rev<<1) + (n | 0)

I tried this in leetcode IDE but it didnt work im not sure why, does anyone know why this doesn't work? and if you know any. other better approaches to do this, it would be great!

  • `n | 0` equals `n`, so it's not the same as `n & 1`. You may want to review [Bitwise operation and usage](https://stackoverflow.com/q/1746613/13843268). – sj95126 Oct 26 '22 at 04:35

1 Answers1

1

There are ways to use bitwise OR, as long as extra operations are allowed.

Using De Morgan's law, A | B = ~(~A & ~B), we can derive that n & 1 = ~(~n | -2). That looks somewhat like what you tried, but with bitwise negations (as required by De Morgan's law) and note that ~1 = -2, it's not zero, only the least significant bit is zero.

Another option is (n | -2) + 2.

harold
  • 61,398
  • 6
  • 86
  • 164