1. 程式人生 > >leetcode-190-顛倒二進位制位(reverse bits)-java

leetcode-190-顛倒二進位制位(reverse bits)-java

題目及測試

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; } }