|
| 1 | +// TC: O(1) |
| 2 | +// SC: O(1) |
| 3 | +function reverseBits(n: number): number { |
| 4 | + let stack: number[] = []; |
| 5 | + |
| 6 | + while (stack.length < 32) { |
| 7 | + stack.push(n % 2); |
| 8 | + n = Math.floor(n / 2); |
| 9 | + } |
| 10 | + |
| 11 | + let output: number = 0; |
| 12 | + let scale: number = 1; |
| 13 | + |
| 14 | + while (stack.length > 0) { |
| 15 | + output += stack.pop()! * scale; |
| 16 | + scale *= 2; |
| 17 | + } |
| 18 | + |
| 19 | + return output; |
| 20 | +} |
| 21 | + |
| 22 | +// TC: O(1) |
| 23 | +// SC: O(1) |
| 24 | +/* |
| 25 | +function reverseBits(n: number): number { |
| 26 | + let result = 0; |
| 27 | +
|
| 28 | + for (let i = 0; i < 32; i++) { |
| 29 | + let bit = n & 1; |
| 30 | + result = (result << 1) | bit; |
| 31 | + n = n >>> 1; |
| 32 | + } |
| 33 | +
|
| 34 | + return result >>> 0; |
| 35 | +} |
| 36 | +*/ |
| 37 | + |
| 38 | +/* |
| 39 | +n & 1 |
| 40 | +- get last bit |
| 41 | +- equivalent to n % 2 for non-negative integer |
| 42 | +
|
| 43 | +n << 1 |
| 44 | +- left shift (multiply by 2) |
| 45 | +
|
| 46 | +n >>> 1 |
| 47 | +- Unsigned right shift (divide by 2) |
| 48 | +- ignores sign |
| 49 | +
|
| 50 | +n >>> 0 |
| 51 | +- no shift, just cast to unsigned |
| 52 | + |
| 53 | +const signed = -1; // Binary: 11111111111111111111111111111111 |
| 54 | +const unsigned = signed >>> 0; // 4294967295 |
| 55 | +
|
| 56 | +JavaScript/TypeScript only has one number type — a 64-bit float. itwise operations use 32-bit signed integers. |
| 57 | + To return a 32-bit unsigned integer, use >>> 0 on the result. |
| 58 | + |
| 59 | + 🔧 Bitwise Operations in JavaScript — Summary |
| 60 | + 1. Bitwise operations in JavaScript (&, |, ^, ~, <<, >>, >>>) are always performed on 32-bit signed integers. |
| 61 | +
|
| 62 | + 2. Internally: |
| 63 | + - JavaScript converts your number into a 32-bit signed integer |
| 64 | + - Performs the bitwise operation |
| 65 | + - Then converts it back into a regular 64-bit number (JavaScript's only number type) |
| 66 | +
|
| 67 | + 3. If you need the result as a 32-bit unsigned integer (like for LeetCode problems dealing with uint32): |
| 68 | + - Use >>> 0 at the end of your result |
| 69 | + - This forces the result to be treated as an unsigned 32-bit integer |
| 70 | +*/ |
0 commit comments