您的位置:首页 > 其它

LeetCode(47)-Reverse Bits

2016-04-12 10:08 537 查看

题目:

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


思路:

题意:给定一个无符号数,把他的二进制位转换过来

考虑首先把原数字右移,然后得到右移的数字,赋值给新数字,然后左移动

-

代码:

public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for(int i = 0; i < 32; i++, n >>= 1){
res = res << 1 | (n & 1);
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: