leetcode-190-颠倒二进制位(reverse bits)-java

版权声明:此文章为许诗宇所写,如需转载,请写下转载文章的地址 https://blog.csdn.net/xushiyu1996818/article/details/83270317

题目及测试

package pid190;
/*颠倒二进制位

颠倒给定的 32 位无符号整数的二进制位。

示例:

输入: 43261596
输出: 964176192
解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
     返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。

进阶:
如果多次调用这个函数,你将如何优化你的算法?



*/




public class main {
	
	public static void main(String[] args) {
		int[] testTable = new int[]{43261596,-5,-7,-2147483647};
		for (int ito : testTable) {
			test(ito);
		}
	}
		 
	private static void test(int ito) {
		Solution solution = new Solution();
		int rtn;
		long begin = System.currentTimeMillis();
		
		System.out.print("ito="+ito+" ");		    
		
		System.out.println();
		//开始时打印数组
		
		rtn = solution.reverseBits(ito);//执行程序
		long end = System.currentTimeMillis();	
		
		//System.out.println(ito + ": rtn=" + rtn);
		System.out.println( " rtn=" +rtn);
//		for (int i = 0; i < ito.length; i++) {
//		    System.out.print(ito[i]+" ");
//		}//打印结果几数组
		
		System.out.println();
		System.out.println("耗时:" + (end - begin) + "ms");
		System.out.println("-------------------");
	}

}

解法1(成功,8ms,超慢)
将int的数字每次取最右的一位,将它放在stringbuilder的最后面,取32次,就是颠倒了

最后用biginter转为为int

package pid190;

import java.math.BigInteger;

class Solution {
	// you need treat n as an unsigned value
    public int reverseBits(int n) {
        //正数的二进制开头为0,负数则为1
    	StringBuilder s=new StringBuilder();
    	for(int i=0;i<32;i++){
    		int now=n&1;
    		n>>>=1;
    		s.append(now);
    	}
    	BigInteger bi = new BigInteger(s.toString(), 2);
    	bi.toString(2);
    	return bi.intValue();
    	
    }
}

解法2(别人的)
 设这个数为k,用一个初值为0的数r保存反转后的结果,用1对k进行求与,其结果与r进行相加,再对k向右进行一位移位,对r向左进行一位移位。值到k的最后一位处理完。
 不用string作为中间转化,直接用int

public class Solution {
 public int reverseBits(int n) {
  int result = 0; 
  for (int i = 0; i < 32; i++) {
   result += n & 1;
    n >>>= 1;
     if (i < 31) { 
     result <<= 1; } 
     } 
     return result; } }

猜你喜欢

转载自blog.csdn.net/xushiyu1996818/article/details/83270317