Reverse Bits

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).

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

 

posted @ 2016-07-31 11:50  北叶青藤  阅读(157)  评论(0编辑  收藏  举报