【LeetCode】Reverse Bits 翻转二进制

题目

Reverse Bits

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).

解答

public int reverseBits(int n) {
String valStr = Integer.toBinaryString(n);
//System.out.println(valStr);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 32; i++) {
if (i > valStr.length() - 1) {
builder.append("0");
} else {
builder.append(valStr.charAt(valStr.length() - 1 - i));
}
}
//System.out.println(builder.toString());
//System.out.println(Integer.valueOf(builder.toString(), 2));
return Integer.valueOf(Integer.valueOf(builder.toString(), 2));
}

public int reverseBits(int n) {
int reverse_num = 0, i, temp;
for (i = 0; i < 32; i++) {
temp = (n & (1 << i));
if (temp > 0)
reverse_num |= (1 << ((32 - 1) - i));
}
System.out.println(reverse_num);
return reverse_num;

}

uint32_t reverseBits(uint32_t n) {
unsigned int  NO_OF_BITS = 32;
unsigned int reverse_num = 0, i, temp;

for (i = 0; i < NO_OF_BITS; i++)
{
temp = (n & (1 << i));
if(temp)
reverse_num |= (1 << ((NO_OF_BITS - 1) - i));
}

return reverse_num;
}
12-03 19

04-03 2180
03-27 1323
05-18 970
08-03 3106
06-01 617
03-26 1940
05-22 887
04-25 1306
09-28