您的位置:首页 > 其它

Leetcode-190 Reverse Bits 数字二进制倒置

2015-03-11 14:23 344 查看
问题描述:

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

C++代码实现:

class Solution {
public:
uint32_t reverseBits(uint32_t n) {

uint32_t result = 0;// 表示计算结果
int temp = 0;       //计数判断是否移动了32次,因为n左侧大多数数字为0,故不一定要循环移动24 位

while (n != 0) {
result = (result << 1) | (n & 1);//每一次上一循环计算的result左移一位,并加上从n取出的该位数字(n & 1)
n >>= 1;
++ temp;
}

if(temp < 32)
{
result <<= (32 - temp);
}
return result;

}
};


Java实现:在系统上无法运行通过,不知该如何处理无符号int的问题

public class Reverse_Bits {

// you need treat n as an unsigned value
public long reverseBits(long n) {
long result = 0;// 表示计算结果
int temp = 0;//
int INT_SIZE = Integer.SIZE;//int类型的size大小

while ((n != 0)&&(temp<=INT_SIZE)) {
result = (result << 1) | (n & 1);
n >>= 1;
++temp;
}

if (temp < INT_SIZE) {
result <<= (INT_SIZE - temp);
}
return result;

}

public static void main(String[] args) {

Reverse_Bits reverse_Bits = new Reverse_Bits();

System.out.println(reverse_Bits.reverseBits(2147483648L));
}

}


修改后实现,使用>>>,其余与C代码相同

public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int result = 0;// 表示计算结果
int temp = 0;       //计数判断是否移动了32次,因为n左侧大多数数字为0,故不一定要循环移动24 位

while (n != 0) {
result = (result << 1) | (n & 1);//每一次上一循环计算的result左移一位,并加上从n取出的该位数字(n & 1)
n >>>= 1;
++ temp;
}

if(temp < 32)
{
result <<= (32 - temp);
}
return result;

}
}


在Java代码中直接书写的数字是int类型的,就是说数字的范围在 -2^31 到 2^31 - 1 这个范围之中,无论将这个数字赋值给什么类型。

直接赋值实参为2147483648时,会出现The literal... of type int is out of range的错误,在数组后加上L,或使用Long.phraseLong()解决问题


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: