Leetcode-190. Reverse Bits

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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?

Related problem: Reverse Integer

这个题目比较有意思是在于他传入的字符串可能会使越界的,所以操作起来要小心。 Your runtime beats 36.61% of java submissions.

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
	int result = 0;
        for(int i = 0; i < 32; i ++){
		result = result << 1;
		if( n != 0){
			result += n&1;
			n  >>>= 1;
		}	
	}
	return result;
    }
}




你可能感兴趣的:(算法,java,leetcode,算法)