Explanation of two-pointer method in Java


  • 0
    L
    1. Keep the bitstring in your mind and start traversing from both 0th(start) and 31(end) indices at the same time.
    2. Use n>>>start and n>>>end to figure out the bit value at that particular index. You could as well use 1<<start or 1<<end and & with n to check the values.
    3. If the value at start and end are different, swap them.
    4. Swapping is achieved by ORing to add 1 where it was 0 and removing 1 by doing an XOR with 1 at that bit value.
      public int reverseBits(int n)
      {
        int start = 0;
        int end = 31;
        while (end > start)
        {
          int a = n >>> end & 1;
          int b = n >>> start & 1;
          if ((a ^ b) != 0)
          {
            if (a == 1)
            {
              n ^= 1 << end;
              n |= 1 << start;
            }
            else
            {
              n |= 1 << end;
              n ^= 1 << start;
            }
          }
          start++;
          end--;
        }
        return n;
      }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.