190.Reverse Bits---位运算

题目链接:https://leetcode.com/problems/reverse-bits/description/

题目大意:将数值的二进制反转。

法一(借鉴):由于是无符号32位整型,当二进制反转后会得到一个32位的整型,eclipse中已经无法正常显示了,但是转为二进制还是正确的。至于为什么我也不知道。代码如下(耗时2ms):

 1     public int reverseBits(int n) {
 2         int res = 0;
 3         for(int i = 0; i <= 31; i++) {
 4             //1010->tmp=0,n=101,res=00,
 5             int tmp = n & 1;//取最后一位
 6             n = n >> 1;//右移
 7             res = res<<1;//结果左移一位
 8             res = res | tmp;//将最后一位加到结果左移的那个位上去,也就是最低位上
 9         }
10     //    System.out.println(Integer.toBinaryString(res));
11         //在eclipse里会显示错误,因为res已经移位形成了32位的数,已经无法正常显示了
12         //但是当转为二进制的时候是正常的
13         return res;
14     }
View Code

其他的解法:http://blog.csdn.net/feliciafay/article/details/44536827

原文地址:https://www.cnblogs.com/cing/p/8039738.html