leetcode题记——Reverse Bits

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).

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
    	String s1 = Integer.toBinaryString(n);//int转为二进制数组
    	StringBuilder r = new StringBuilder();//存储结果
    	
    	for(int i = s1.length()-1;i>=0;i--) 
    		r.append(s1.charAt(i));
    	
    	for(int i = 32-s1.length()-1;i>=0;i--) //初始的0补在结果最后
    		r.append('0');
    	
    	String s2 = r.toString();
    	
    	long r1 = Long.parseLong(s2, 2); //int范围为-2^31~2^31-1,当转置为32位时,会发生溢出

    	return (int)r1;

    }
}



已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页