# 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);
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/binary/190.-reverse-bits.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
