题意:
将一个无符号整数转化的二进制反转,输出反转的二进制对应的无符号整数。
初步分析:不断除以2,将余数加上(上一步的结果乘上2),直到n<=0,如果未满32步,则继续将结果乘2(直到到达32步),感觉没什么问题,但结果有错。
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int rev = 0;
int i = 0;
while(n > 0)
{
rev = rev*2 + n%2;
n /= 2;
i++;
while(n <= 0 && i<32)
{
rev = rev*2;
i++;
}
}
return rev;
}
}
自己跑了一下,发现小数字是没有问题的,但是太大了就不行,还是用字符串的方法。
改用字符串的方法:
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
String str = Integer.toBinaryString(n);
while (str.length() < 32) {
str = "0" + str;
}
char[] arr = str.toCharArray();
int s = 0;
int e = str.length()-1;
while(s < e){
char t = arr[s];
arr[s] = arr[e];
arr[e] = t;
s++;
e--;
}
String ret = new String(arr);
long result = Long.parseLong(ret,2);
return (int)result;
}
}