Skip to content

Commit 9807b1a

Browse files
committed
add reverse bits
1 parent 974950a commit 9807b1a

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

reverse-bits/README.md

Whitespace-only changes.

reverse-bits/Solution.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
public class Solution {
2+
3+
// from JDK Integer.reverse
4+
5+
/**
6+
* Returns the value obtained by reversing the order of the bits in the
7+
* two's complement binary representation of the specified {@code int}
8+
* value.
9+
*
10+
* @param i the value to be reversed
11+
* @return the value obtained by reversing order of the bits in the
12+
* specified {@code int} value.
13+
* @since 1.5
14+
*/
15+
public static int reverse(int i) {
16+
// HD, Figure 7-1
17+
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
18+
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
19+
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
20+
i = (i << 24) | ((i & 0xff00) << 8) |
21+
((i >>> 8) & 0xff00) | (i >>> 24);
22+
return i;
23+
}
24+
25+
// you need treat n as an unsigned value
26+
public int reverseBits(int n) {
27+
return reverse(n);
28+
}
29+
}

reverse-bits/index.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
layout: solution
3+
title: Reverse Bits
4+
date: 2015-03-07 19:33:34+08:00
5+
leetcode_id: 190
6+
---
7+
{% assign leetcode_name = {{page.path | remove: '/index.md'}} %}
8+
{% assign leetcode_readme = {{leetcode_name | append: '/README.md' | prepend: '_root/' }} %}
9+
{% include {{leetcode_readme}} %}

0 commit comments

Comments
 (0)