leetcode Reverse Bits

这个题目有点奇怪。要求输出一个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--;  
        }  
    }  
  
}

可以看到大神的解法正确不说还很快。所以要向他们学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值