Leetcode Reverse Bits

题目地址:https://leetcode.com/problems/reverse-bits/

题目分析:可以4bit为单位,0翻转对应0,1翻转对应8.....15翻转对应15,将这些翻转信息保存在数组中即可以O(1)的空间复杂度换来很好的时间复杂度

题目解答:

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int[] tb = {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15};
        int ret = 0;
        int msk = 15;
        for(int i = 0;i<8;i++){
            int curr = n&msk;
            ret = ret<<4;
            ret |= tb[curr];
            n = n>>>4;
        }
        return ret;
    }
}

 

posted @ 2015-04-11 17:04  buptubuntu  阅读(89)  评论(0)    收藏  举报