# 190. Reverse Bits

{% embed url="<https://leetcode.com/problems/reverse-bits/description/>" %}

#### [Java](https://leetcode.com/problems/reverse-bits/solutions/54746/java-solution-and-optimization/)

#### [javascript](https://leetcode.com/problems/reverse-bits/solutions/55011/javascript-solution/)

[@shurui](https://leetcode.com/shurui) using << coerces the int to a 32-bit *signed* int, so the tests fail because it's interpreted as a negative value.

* Using \*= coerces it back to a JS float, which is interpreted as the correct positive value (JS floats can store its up to 53 bits)
* You can still use `result = result << 1` if you either (a) Math.abs(result) at the end before returning or (b) `return result >>> 0` before returning. Both have the same effect.

This is documented here: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators>

Without reading that or just knowing it, there's no way to reason out why << doesn't work.

Try reassigning result:

```sql
result = result << 1
```

which is the same as:

```jsx
result *= 2
```

> time: O(N)

> space: O(32) > O(1)

```jsx
/**
 * @param {number} n - a positive integer
 * @return {number} - a positive integer
 */
var reverseBits = function(n) {
    const bi = n.toString(2);
    const paded = bi.padStart(32, '0');
    const reversed = [...paded].reverse().join('');

    return parseInt(reversed, 2);
};
```
