Skip to content

Commit 618c7df

Browse files
committed
solve: reverse bits
1 parent 99c7c92 commit 618c7df

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

reverse-bits/evan.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {number} n - a positive integer
3+
* @return {number} - a positive integer
4+
*/
5+
var reverseBits = function (n) {
6+
const binary = n.toString(2).padStart(32, "0");
7+
const reversedBinary = binary.split("").reverse().join("");
8+
9+
return parseInt(reversedBinary, 2);
10+
};
11+
12+
/**
13+
* Time Complexity: O(1)
14+
* Reason:
15+
* - Each step involves operations on fixed-length strings or arrays (maximum length of 32).
16+
* - Thus, the time complexity for each operation is constant, resulting in an overall time complexity of O(1).
17+
*
18+
* Space Complexity: O(1)
19+
* Reason:
20+
* - The algorithm uses a constant amount of space for the binary string, reversed binary string, and intermediate arrays.
21+
* - Each of these has a fixed length of 32, so the overall space complexity is O(1).
22+
*/

0 commit comments

Comments
 (0)