[LeetCode 190] Reverse Bits

题目链接:reverse-bits


import java.util.Arrays;


/**
 * 
		Reverse bits of a given 32 bits unsigned integer.
		
		For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), 
		return 964176192 (represented in binary as 00111001011110000010100101000000).
		
		Follow up:
		If this function is called many times, how would you optimize it?
 *
 */

public class ReverseBits {

	
	
	
//	600 / 600 test cases passed.
//	Status: Accepted
//	Runtime: 270 ms
//	Submitted: 0 minutes ago
	
	
	// you need treat n as an unsigned value
	//把n当初无符号数
    static int reverseBits(int n) {        
        
    	//存储反转后各位上的数 bits[高位...低位]
    	int[] bits = new int[32];
        int num = 0;
        
        Arrays.fill(bits, 0);
        
        //如果是是负数 ,则将符号位直接放到bits[31]上
        if(n < 0) {
        	n = n ^ Integer.MIN_VALUE;	//异或
        	bits[31] = 1;
        }
        
        //计算各位上的数
        for (int i = 0; i < bits.length - 1; i++) {
			bits[i] = n % 2;
			n /= 2;
		}
        
        for(int i = 1; i < bits.length; i ++) {
        	num <<= 1;
        	num += bits[i];
        }
        
        //判断符号位
        return bits[0] == 1 ? num | Integer.MIN_VALUE : num;
    }
	public static void main(String[] args) {
		System.out.println(reverseBits(1));
		System.out.println(reverseBits(43261596));
		System.out.println(reverseBits(-2147483648));

	}

}



版权声明:本文为ever223原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。