LeetCode 190. Reverse Bits 题解
来源:互联网 发布:网络教育学籍查询 编辑:程序博客网 时间:2024/06/17 23:22
题目链接:点击打开链接
先给出最先想到的解法,java代码如下:
public class Solution { public int reverseBits(int n) { // 将整数转为二进制 String binaryString = Integer.toBinaryString(n); // 二进制字符串反转 int length = binaryString.length(); StringBuffer result = new StringBuffer(); for(int i=length-1; i>=0; i--){ char temp = binaryString.charAt(i); result.append(temp); } int len = result.length(); for(int i=len; i<32; i++){ result.append('0'); } String temp = new String(result); // 将反转之后的二进制字符串转为int // 此处注意:若使用Integer.parseInt(temp,2)则当n=1,3...会溢出出错。 // 举例来说,若n=1,反转之后的String字符串为"10000000000000000000000000000000",表示的整数为2147483648 // 而2147483648已经超过了32位有符号数的最大范围,因此抛出异常 Long intResult = Long.parseLong(temp, 2); return intResult.intValue(); }}
显而易见还有更简单的方法——使用位运算:
思路:将32位的无符号整数n右移32次,每次移动取出最低位,赋值给另一个变量result, 对应于n的右移,result对应地左移32次。(result需要先右移,再将n的最低位赋值给result,否则当输入n=2147483648时,会溢出,因为java的int类型是有符号的,能表示的最大的数是2147483647)
public class Solution { public int reverseBits(int n) { int result = 0; for (int i=0; i<32; i++){ // 取出n的最低位 int least = n & 0x01; // n右移一位 n = n >> 1; // 下面两个步骤需要注意:一定要先左移,再赋值。 // 否则当n=2147483648时,result = result | least 会溢出。 // 将result左移一位result = result << 1; // 将n的最低位加到result最后一位 result = result | least; } return result; }}
0 0
- Leetcode题解 190. Reverse Bits
- LeetCode 190. Reverse Bits 题解
- LeetCode题解:Reverse Bits
- LeetCode题解:Reverse Bits
- LeetCode 题解(202) : Reverse Bits
- 【LeetCode】190.Reverse bits
- LeetCode 190. Reverse Bits
- Leetcode 190. Reverse Bits
- 190. Reverse Bits LeetCode
- LeetCode *** 190. Reverse Bits
- LeetCode 190. Reverse Bits
- Leetcode-190. Reverse Bits
- Leetcode 190. Reverse Bits
- LeetCode-190.Reverse Bits
- [leetcode] 190. Reverse Bits
- Leetcode 190. Reverse Bits
- [Leetcode]190. Reverse Bits
- LeetCode 190. Reverse Bits
- JAVA之二维数组
- 二十五,iOS GCD的使用
- 捕获fatal error形成报警机制
- 正则表达式处理字符串中的img,去除style属性,添加自适应图片的类
- Notepad20170302
- LeetCode 190. Reverse Bits 题解
- CCF认证考试201612-3 权限查询题解
- iOS 保持界面流畅的技巧
- Vue过渡(动画)- transition组件
- [leetcode] 520. Detect Capital
- 终端最常用快捷键
- 跟踪(Tracking)资料汇总
- 51nod1686 第K大区间 【二分】
- SSH三大框架的工作原理及流程