190. Reverse Bits
来源:互联网 发布:逆波兰表达式算法 java 编辑:程序博客网 时间:2024/06/05 06:45
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).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
思路:
将32位的无符号整数n右移32次,每次移动取出最低位,赋值给另一个变量result, 对应于n的右移,result对应地左移32次。(result需要先右移,再将n的最低位赋值给result,否则当输入n=2147483648时,会溢出,因为java的int类型是有符号的,能表示的最大的数是2147483647)。
public class Solution { // you need treat n as an unsigned value 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
- 190. Reverse Bits
- Leetcode 190. Reverse Bits
- 190. Reverse Bits LeetCode
- 190. Reverse Bits
- 190. Reverse Bits
- 190. Reverse Bits
- LeetCode *** 190. Reverse Bits
- 190. Reverse Bits
- 190. Reverse Bits
- LeetCode 190. Reverse Bits
- 190. Reverse Bits
- 190. Reverse Bits
- Leetcode-190. Reverse Bits
- Leetcode 190. Reverse Bits
- LeetCode-190.Reverse Bits
- [leetcode] 190. Reverse Bits
- paddlepaddle通过ssh登陆后,进行后付费深度学习example test
- #Android学习计划# #第四周# 话题:关于startActivityForResult
- 最大连续子数列和
- SQL 按时间区间选取
- 嵌入式项目1--UCOSIII移植
- 190. Reverse Bits
- 图的存储结构
- Coursera 编程题 #3 运算符重载 写一个二维数组类 Array2心得
- TCP/UDP 区别
- 【工具使用】图形化工具----Jeddict
- python 之 python3内置函数
- 模拟双色球案例
- Hadoop之YARN在单节点上运行
- vue-router嵌套路由