leetcode | 190. reversed bits

Reversed given 32-bit unsigned binary integer.

Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
explained: 00000010100101000001111010011100 input binary string unsigned integer 43261596,
the flow returns 964,176,192, which is 00111001011110000010100101000000 binary representation.

Example 2:
Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
explained: input binary string 11111111111111111111111111111101 4294967293 unsigned integer,
so it returns 3221225471 10101111110010110010011101101001 as binary representation.

Thinking

Time complexity of O (n), the spatial complexity is O (1).

Code

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int ans = 0;
        for(int i = 0; i < 32; i++) {
            int temp = (n>>i & 1);
            ans |= temp << (31 - i);
        }
        return ans;
    }
}

Links: https://leetcode-cn.com/problems/reverse-bits

Guess you like

Origin www.cnblogs.com/ustca/p/12307699.html