Reverse bits

Run Settings
LanguageJavaScript
Language Version
Run Command
function reverseBits(x) { // 0 is a good starting point for most bitwise operations and most number problems in general let output = 0; while (x !== 0) { output = output << 1; // shift output to the left by one if(x & 1 === 1) { // Check the last bit of our input by ANDing it with 1 to check if it's equal to one true for 0 and 1 output = output | 1; // ORing output with 1 is using logical OR } x = x >> 1; // A bitwise shift to the right to make sure we knock off the last bit we just processed and add 0 to the left return output; } } // We must mirror the action for every bit processed on the left it must be effected on the right as well /* Time & Space complexity Time: O(n) out input decreases in size by 1 bit each time Space: O(i) */
Editor Settings
Theme
Key bindings
Full width
Lines