1. Description
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
2. Runtime Distribution
3. Submission Details
4. Example
Input: 43261596
Ouput: 964176192
5. Code
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active"]
public int reverseBits(int n) { for (int i = 0; i < 16; i++) { int lowBit = (n >> i) & 1; int highBit = (n >> (31 - i)) & 1; if ((lowBit ^ highBit) == 1) { n ^= (1 << i) | (1 << 31 - i); } } return n; }
[/restab]
[/restabs]
6.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active" ]
public class LeetCode0190 { public int reverseBits(int n) { for (int i = 0; i < 16; i++) { int lowBit = (n >> i) & 1; int highBit = (n >> (31 - i)) & 1; if ((lowBit ^ highBit) == 1) { n ^= (1 << i) | (1 << 31 - i); } } return n; } public static void main(String[] args) { LeetCode0190 leetcode = new LeetCode0190(); System.out.println(leetcode.reverseBits(43261596)); } }
[/restab]
[/restabs]
Comments | NOTHING