p190

LeetCode p190 Reverse Bits 题解

1.题目:

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).

题意:

将一个数的二进制反转

2.解题思路:

位运算

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int ans = 0, count = 1;
for (int i = 0; i < 31; i++) {
ans += (1 & n);
// System.out.println(ans);
n = n >> 1;
count = count * 2;
ans = ans << 1;
}
ans += (1 & n);
return ans;
}
}

4.一些总结: