Skip to content

Commit

Permalink
reverse-bit solution
Browse files Browse the repository at this point in the history
  • Loading branch information
Jaehyeon Robert Han authored and Jaehyeon Robert Han committed Dec 24, 2024
1 parent b57c526 commit da5c5c6
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions reverse-bits/Zioq.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* @param {number} n - a positive integer
* @return {number} - a positive integer
*/
var reverseBits = function(n) {
let result = 0; //Initial value
for (let i=0; i < 32; i++) { //The loop iterates 32 times, as the input n is a 32-bit unsigned integer
result = (result << 1) | (n & 1); // Shift the result to the left by 1 bit OR it with the least significant bit of n.
n >>= 1; // Shifts the bits of n one place to the right, effectively "removing" the processed LSB.
}
return result >>> 0;
};
/*
Time Complexity: O(1), because we always loop exactly 32 times, regardless of the input.
Space Complexity: O(1), because we use a constant amount of space.
*/



0 comments on commit da5c5c6

Please sign in to comment.