首页 > 其他 > 详细

[LeetCode 190] Reverse Bits

时间:2015-03-22 15:06:10      阅读:132      评论:0      收藏:0      [点我收藏+]

题目链接: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));

	}

}


[LeetCode 190] Reverse Bits

原文:http://blog.csdn.net/ever223/article/details/44537445

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!