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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-08
  • 2021-12-28
  • 2022-03-07
  • 2021-11-28
  • 2022-12-23
猜你喜欢
  • 2021-09-16
  • 2021-06-08
  • 2022-02-05
  • 2021-06-24
  • 2021-12-11
  • 2021-12-04
  • 2022-01-01
相关资源
相似解决方案