首页 > 其他 > 详细

*Reverse Bits

时间:2015-07-30 00:18:21      阅读:259      评论:0      收藏:0      [点我收藏+]

题目

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?

 

思路:

该题的思路与Reverse Integer类似,这里是对二进制数进行转置,我们可以使用移位的方法进行,对原数不断取最后一位:n & 1

然后不断右移:n=n>>1

而对结果数不断左移或上原数的最后一位:res=res<<1; res=res | (n & 1)

由于位数是确定的,因此只需要移位31次即可。

 

代码如下:

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int res= n & 1;
        for(int i=1;i<=31;i++)
        {
            n=n>>1; //不断向右移动
            res=res<<1; //不断向左移动
            res=res | (n & 1);
        }
        return res;

    }
}

 

reference: http://pisxw.com/algorithm/Reverse-Bits.html

*Reverse Bits

原文:http://www.cnblogs.com/hygeia/p/4687757.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!