LeetCode - Algorithms - 190. Reverse Bits

Simple as it labled, The problem is puzzled for it has problem with unsigned integer, and neith Java nor JavaScript has unsigned type. I’d like to pass it for some time. The code copied from Web passed in LeetCode, but it output wrong result for some input number.

Java

solution from 190. Reverse Bits

There is no unsigned integer type. If you need to work with unsigned values originating outside your program, they must be stored in a larger signed type. For example, unsigned bytes produced by an analog-to-digital converter, can be read into variables of type short. — THE Java™ Programming Language, Fourth Edition, By Ken Arnold, James Gosling, David Holmes

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for (int i = 31; i >= 0; i--) {
if (((n >> i) & 1) == 1) {
res += (1 << (31 - i));
}
}
return res;
}
}

Submission Detail

  • 600 / 600 test cases passed.
  • Runtime: 1 ms
  • Your runtime beats 100.00 % of java submissions.

JavaScript

solution from 190. Reverse Bits – JavaScript 代码

1
2
3
4
5
6
7
8
9
10
11
/**
* @param {number} n - a positive integer
* @return {number} - a positive integer
*/
var reverseBits = function(n) {
var result = 0;
for (var i = 0; i < 32; ++i) {
result |= (n >> i & 0x1) << (31 - i);
}
return result >>> 0;
};

Submission Detail

  • 600 / 600 test cases passed.
  • Runtime: 88 ms
  • Your runtime beats 12.00 % of javascript submissions.