[LeetCode-190] Reverse Bits(反转位)

来源:互联网 发布:淘宝介入买家怎么赢 编辑:程序博客网 时间:2024/05/31 19:49

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?


http://blog.csdn.net/xy010902100449/article/details/48241171

【分析】前面有做过反转整数案例,不过这里输入时一个u32 数字,反转之后也不会出现溢出,所以不需要考虑数字溢出的情况。思路如下:通过位移位先将最低位的数字和1相&移动到第31位(最高位),存下来。通过移动输入的u32的数字一位,重新上述操作,和1相&移动第30位(次高位),通过控制 index 即可实现。代码如下:

uint32_t reverseBits(uint32_t n) {    if(0 == n)        return 0;    int index = 32;    uint32_t reverseBitsNum = 0;    while(n) {        reverseBitsNum |= (n&1)<<index; /*高位->低位*/        n = n>>1 /*右移动移位*/        index --;    }    return reverseBitsNum;}
0 0
原创粉丝点击