190.Reverse Bits---位运算

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

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

法一(借鉴):因为是无符号32位整型,当二进制反转后会获得一个32位的整型,eclipse中已经没法正常显示了,可是转为二进制仍是正确的。至于为何我也不知道。代码以下(耗时2ms):spa

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

相关文章
相关标签/搜索