LeetCode 190. Reverse Bits
原题链接在这里:https://leetcode.com/problems/reverse-bits/
题目:
Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000 Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: 11111111111111111111111111111101 Output: 10111111111111111111111111111111 Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
Note:
- Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
- In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above the input represents the signed integer
-3
and the output represents the signed integer-1073741825
.
题解:
新学了一种API, Integer.reverse()可以直接返回binary的reverse. 参考链接:http://www.tutorialspoint.com/java/lang/integer_reverse.htm
Method 2 res左移一位后加上n的最右一位digit.
Time Complexity: O(1). 一共左移了32位.
Space O(1).
AC Java:
1 public class Solution { 2 // you need treat n as an unsigned value 3 public int reverseBits(int n) { 4 //Method 1 5 //return Integer.reverse(n); 6 7 //Method 2 8 int res = 0; 9 for(int i = 0; i<32; i++){ 10 res <<= 1; 11 res += ((n>>i)&1); 12 } 13 return res; 14 } 15 }
Follow up 要求 this function is called many times.
把int 拆成 4个byte 分别reverse 反着加回去. 同时维护HashMap, key是byte, value是reverse 这个byte后的结果int.
若function 被call了很多次,那么大部分的byte都已经有了对应的reverse value存在HashMap中了。
AC Java:
1 public class Solution { 2 HashMap<Byte, Integer> hm = new HashMap<Byte, Integer>(); 3 4 public int reverseBits(int n) { 5 byte [] bytes = new byte[4]; 6 7 //convert int into bytes 8 for(int i = 0 ; i<4; i++){ 9 bytes[i] = (byte)((n>>>8*i) & 0xFF); 10 } 11 12 int res = 0; 13 for(int i = 0; i<4; i++){ 14 res <<= 8; 15 res += reverseByte(bytes[i]); 16 } 17 18 return res; 19 } 20 21 private int reverseByte(Byte b){ 22 if(hm.containsKey(b)){ 23 return hm.get(b); 24 } 25 26 int val = 0; 27 for(int i = 0; i<8; i++){ 28 val <<= 1; 29 val += ((b>>>i)&1); 30 } 31 hm.put(b, val); 32 return val; 33 } 34 }
标签:
LeetCode
, Bit Manipulation
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
· 上周热点回顾(3.24-3.30)