190. Reverse Bits Java Solutin

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

Related problem: Reverse Integer

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

 1 public class Solution {
 2     // you need treat n as an unsigned value
 3     public int reverseBits(int n) {
 4         //return Integer.reverse(n);
 5         int result = 0;
 6         for(int i = 0 ;i < 32; i++){
 7             int tmp = (n&1);
 8             n = n >> 1;
 9             result = result << 1;
10             result += tmp;
11         }
12         return result;
13     }
14 }

使用 Integer.reverse() API 直接AC。

每一次取出n的末尾二进制数字,result左移移位,将移出的数字加到result末尾,循环32次后,既得结果。

原文地址:https://www.cnblogs.com/guoguolan/p/5396699.html