二刷 06/2022
Version #2
Time O(32)
Space O(1)
Runtime: 2 ms, faster than 27.48% of Java online submissions for Reverse Bits.
Memory Usage: 41.5 MB, less than 91.42% of Java online submissions for Reverse Bits.
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++) {
result = (result << 1) + (n & 1);
n >>>= 1;
}
return result;
}
}
一刷
Version #212.19 %
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++) {
result = (result << 1) | (n & 1);
n >>>= 1;
}
return result;
}
}
Version # 1 swap
28.24 %
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
for (int i = 0; i < 16; i++) {
n = swapBits(n, i, 32 - i - 1);
}
return n;
}
private int swapBits(int n, int i, int j) {
int a = (n >>> i) & 1;
int b = (n >>> j) & 1;
if ((a ^ b) != 0) {
return n ^= (1 << i) | (1 << j);
}
return n;
}
}
No comments:
Post a Comment