这个题目有点奇怪。要求输出一个32位的int。还是无符号的。我用java实在没想到怎么处理。所以就上网百度了一下。看到了别人的解法
题目链接 点击打开链接
大神的解法 大神的地址点击打开链接
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;
}
}
我的解法
import java.util.Scanner;
import java.util.Stack;
import java.math.*;
public class Solution {
private static int inArr[]=new int[32];
private static long inNumber;
public static void main(String args[])
{
Scanner in =new Scanner(System.in);
inNumber=in.nextInt();
inNumberTransform();
rev(inArr,0,31);
// for(int i=0;i<32;i++)
// {
// System.out.printf("%d",inArr[i]);
// }
System.out.println("");
System.out.println(getNumber());
}
public static long getNumber()
{
long result=0;
int weight=1;
for(int i=31;i>=0;i--)
{
result=result+inArr[i]*weight;
weight*=2;
}
return result;
}
public static void inNumberTransform()
{
for(int i=0;i<32;i++)
{
inArr[i]=0;
}
int k=31;
while(inNumber!=0)
{
inArr[k]=(int)(inNumber%2);
inNumber/=2;
k--;
}
}
public static void rev(int []arr,int l,int r)
{
int temp;
int right=r;
for(int left=l;left<right;left++)
{
temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
right--;
}
}
}
可以看到大神的解法正确不说还很快。所以要向他们学习