• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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 as 00111001011110000010100101000000).

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

Related problem: Reverse Integer

Reverse Integer那道题会考虑溢出,因为那是reverse each digit,这里不会溢出,因为reverse的是each bit

 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             int bit = (n>>i) & 1;
 7             res |= bit<<(31-i); 
 8         }
 9         return res;
10     }
11 }

 Q:如果该方法被大量调用,或者用于处理超大数据(Bulk data)时有什么优化方法?
A:这其实才是这道题的精髓,考察的大规模数据时算法最基本的优化方法。其实道理很简单,反复要用到的东西记下来就行了,所以我们用Map记录之前反转过的数字和结果。更好的优化方法是将其按照Byte分成4段存储,节省空间。参见这个帖子。How to optimize if this function is called multiple times? We can divide an int into 4 bytes, and reverse each byte then combine into an int. For each byte, we can use cache to improve performance.

 1 // cache
 2 private final Map<Byte, Integer> cache = new HashMap<Byte, Integer>();
 3 public int reverseBits(int n) {
 4     byte[] bytes = new byte[4];
 5     for (int i = 0; i < 4; i++) // convert int into 4 bytes
 6         bytes[i] = (byte)((n >>> 8*i) & 0xFF);
 7     int result = 0;
 8     for (int i = 0; i < 4; i++) {
 9         result += reverseByte(bytes[i]); // reverse per byte
10         if (i < 3)
11             result <<= 8;
12     }
13     return result;
14 }
15 
16 private int reverseByte(byte b) {
17     Integer value = cache.get(b); // first look up from cache
18     if (value != null)
19         return value;
20     value = 0;
21     // reverse by bit
22     for (int i = 0; i < 8; i++) {
23         value += ((b >>> i) & 1);
24         if (i < 7)
25             value <<= 1;
26     }
27     cache.put(b, value);
28     return value;
29 }

 

posted @ 2015-03-14 07:06  neverlandly  阅读(773)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3