Version I - swap bits

Mistakes!!
  • don't forget to clear bits
public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int i = 0;
        int j = 31;

        while (i < j) {
            if ((n & 1 << j) == 0 && (n & 1 << i) != 0) {
                n |= 1 << j;
                n &= ~(1 << i);
            } else if ((n & 1 << j) != 0 && (n & 1 << i) == 0) {
                n |= 1 << i;
                n &= ~(1 << j);
            }
            i++;
            j--;
        }

        return n;
    }
}

results matching ""

    No results matching ""