190Reverse Bits

来源:互联网 发布:sql学生成绩表 编辑:程序博客网 时间:2024/05/18 15:28

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

uint32_t reverseBits(uint32_t n) {    unsigned char arr[4];    int i = 0;    arr[0] = ((unsigned char*)&n)[3];    arr[1] = ((unsigned char*)&n)[2];    arr[2] = ((unsigned char*)&n)[1];    arr[3] = ((unsigned char*)&n)[0];        for(int i=0; i<4; i++)    {        arr[i] = (arr[i] & 0x55) << 1 | (arr[i] & 0xAA) >> 1;          arr[i] = (arr[i] & 0x33) << 2 | (arr[i] & 0xCC) >> 2;          arr[i] = (arr[i] & 0x0F) << 4 | (arr[i] & 0xF0) >> 4;     }        return *((uint32_t*)arr);}
600 / 600 test cases passed.
Status: 

Accepted

Runtime: 4 ms


0 0
原创粉丝点击