-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseBits.java
34 lines (32 loc) · 968 Bytes
/
ReverseBits.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// https://leetcode.com/problems/reverse-bits/
// #bit-manipulation
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for (int i = 0; i < 32; i++) {
res <<= 1;
int end = n & 1;
res = res | end;
n >>= 1;
}
return res;
}
// // you need treat n as an unsigned value
// public int reverseBits(int n) {
// int mask = 1 << 31;
// int res = 0;
// for (int i = 0; i <= 31; i++) {
// // System.out.println(Integer.toBinaryString(n));
// if ((n & 1) > 0) {
// res |= mask;
// }
// n >>= 1;
// mask >>= 1;
// // System.out.println(Integer.toBinaryString(res));
// System.out.println(Integer.toBinaryString(mask));
// // System.out.println("nn");
// }
// return res;
// }
}