-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0190_reverse_bits.html
More file actions
414 lines (348 loc) · 14.9 KB
/
0190_reverse_bits.html
File metadata and controls
414 lines (348 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reverse Bits - LeetCode 190</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#0190</span> Reverse Bits</h1>
<p><strong>Problem:</strong> Reverse bits of a given 32 bits unsigned integer.</p>
<p><strong>Pattern:</strong> Bit Manipulation - Extract bits from right, build result from left</p>
<div class="problem-meta">
<span class="meta-tag">💻 Bit</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0190_reverse_bits/0190_reverse_bits.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>A linked list is like a <strong>chain of train cars</strong>:</p>
<ul>
<li><strong>Each node:</strong> Contains data and points to next node</li>
<li><strong>Traversal:</strong> Follow the chain one node at a time</li>
<li><strong>Modification:</strong> Redirect links to rearrange</li>
<li><strong>Two pointers:</strong> Often use slow/fast pointers</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="visualization">
<svg id="mainSvg"></svg>
</div>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
<div class="speed-control">
<label for="speed">Speed:</label>
<input type="range" id="speed" min="100" max="2000" value="600">
</div>
</div>
<div class="status" id="status">Click "Step" to reverse bits one at a time</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Bit Position:</span>
<span id="bitPos">-</span>
</div>
<div class="var-item">
<span class="var-label">Current Bit:</span>
<span id="currentBit">-</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Reverse Bits
Problem from LeetCode: https://leetcode.com/problems/reverse-bits/
Description:
Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
"""
class Solution:
def reverse_bits(self, n: int) -> int:
"""
Reverse the bits of a 32-bit unsigned integer.
Args:
n: 32-bit unsigned integer
Returns:
int: Integer with reversed bits
"""
reverse = 0
for i in range(32):
reverse = reverse << 1
reverse = reverse | n & 1
n = n >> 1
return reverse
def reverse_bits_pythonic(self, n: int) -> int:
"""
Reverse bits using Python's built-in bin function.
Args:
n: 32-bit unsigned integer
Returns:
int: Integer with reversed bits
"""
# Convert to binary string, remove '0b' prefix, pad to 32 bits, reverse, convert back to int
binary_str = bin(n)[2:].zfill(32)
reversed_str = binary_str[::-1]
return int(reversed_str, 2)
def reverse_bits_divide_conquer(self, n: int) -> int:
"""
Reverse bits using a divide and conquer approach.
Args:
n: 32-bit unsigned integer
Returns:
int: Integer with reversed bits
"""
# Swap adjacent bits
n = ((n & 0x55555555) << 1) | ((n & 0xAAAAAAAA) >> 1)
# Swap adjacent pairs
n = ((n & 0x33333333) << 2) | ((n & 0xCCCCCCCC) >> 2)
# Swap adjacent nibbles
n = ((n & 0x0F0F0F0F) << 4) | ((n & 0xF0F0F0F0) >> 4)
# Swap adjacent bytes
n = ((n & 0x00FF00FF) << 8) | ((n & 0xFF00FF00) >> 8)
# Swap adjacent 16-bit fields
n = ((n & 0x0000FFFF) << 16) | ((n & 0xFFFF0000) >> 16)
return n
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
n1 = 0b00000010100101000001111010011100 # 43261596 in decimal
result1 = solution.reverse_bits(n1)
print(f"Example 1: {n1} ({bin(n1)}) -> {result1} ({bin(result1)})")
print(f"Expected output: 964176192 (0b111001011110000010100101000000)")
# Example 2
n2 = 0b11111111111111111111111111111101 # 4294967293 in decimal
result2 = solution.reverse_bits(n2)
print(f"Example 2: {n2} -> {result2}")
print(f"Expected output: 3221225471")
# Compare with Pythonic approach
print("\nUsing Pythonic approach:")
print(f"Example 1: {solution.reverse_bits_pythonic(n1)}")
# Compare with divide and conquer approach
print("\nUsing divide and conquer approach:")
print(f"Example 1: {solution.reverse_bits_divide_conquer(n1)}")
</pre>
</div>
</div>
</div>
<script>
// Use 8 bits for visualization simplicity
const BITS = 8;
const originalNum = 43; // 00101011
let n = originalNum;
let result = 0;
let bitPosition = 0;
let autoRunning = false;
let autoTimer = null;
const width = 800;
const height = 400;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
function toBinary(num, bits = BITS) {
return (num >>> 0).toString(2).padStart(bits, '0');
}
function draw() {
svg.selectAll("*").remove();
const originalBits = toBinary(originalNum);
const currentBits = toBinary(n);
const resultBits = toBinary(result);
// Title
svg.append("text")
.attr("x", width / 2)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Reversing bits of ${originalNum} (${BITS}-bit demo)`);
// Original number
svg.append("text")
.attr("x", 100)
.attr("y", 80)
.attr("text-anchor", "end")
.attr("font-weight", "bold")
.text("Original:");
drawBitArray(originalBits, 120, 60, "original");
// Arrow showing extraction
if (bitPosition < BITS) {
const extractX = 120 + (BITS - 1 - bitPosition) * 45 + 17;
svg.append("path")
.attr("d", `M${extractX},100 L${extractX},130`)
.attr("stroke", "#f57c00")
.attr("stroke-width", 2)
.attr("marker-end", "url(#arrow)");
svg.append("text")
.attr("x", extractX)
.attr("y", 150)
.attr("text-anchor", "middle")
.attr("fill", "#f57c00")
.attr("font-size", "12px")
.text(`Extract bit ${bitPosition}`);
}
// Current n (remaining)
svg.append("text")
.attr("x", 100)
.attr("y", 200)
.attr("text-anchor", "end")
.text("n (shifted):");
drawBitArray(currentBits, 120, 180, "current");
// Result being built
svg.append("text")
.attr("x", 100)
.attr("y", 300)
.attr("text-anchor", "end")
.attr("font-weight", "bold")
.text("Result:");
drawBitArray(resultBits, 120, 280, "result");
// Arrow showing placement
if (bitPosition > 0 && bitPosition <= BITS) {
const placeX = 120 + (bitPosition - 1) * 45 + 17;
svg.append("path")
.attr("d", `M${placeX},250 L${placeX},275`)
.attr("stroke", "#4caf50")
.attr("stroke-width", 2)
.attr("marker-end", "url(#arrow-green)");
}
// Values
svg.append("text")
.attr("x", 520)
.attr("y", 80)
.attr("font-size", "14px")
.text(`= ${originalNum}`);
svg.append("text")
.attr("x", 520)
.attr("y", 200)
.attr("font-size", "14px")
.text(`= ${n}`);
svg.append("text")
.attr("x", 520)
.attr("y", 300)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", bitPosition === BITS ? "#4caf50" : "#333")
.text(`= ${result}`);
// Formula
svg.append("text")
.attr("x", width / 2)
.attr("y", 360)
.attr("text-anchor", "middle")
.attr("font-family", "monospace")
.attr("font-size", "14px")
.text(bitPosition < BITS ?
`bit = (n >> ${bitPosition}) & 1 = ${(n >> bitPosition) & 1}, result |= bit << ${BITS - 1 - bitPosition}` :
`Complete! ${originalNum} reversed = ${result}`);
// Define arrow markers
svg.append("defs").html(`
<marker id="arrow" markerWidth="10" markerHeight="10" refX="5" refY="5" orient="auto">
<path d="M0,0 L10,5 L0,10 Z" fill="#f57c00"/>
</marker>
<marker id="arrow-green" markerWidth="10" markerHeight="10" refX="5" refY="5" orient="auto">
<path d="M0,0 L10,5 L0,10 Z" fill="#4caf50"/>
</marker>
`);
}
function drawBitArray(bits, x, y, type) {
const bitArray = bits.split('');
bitArray.forEach((bit, i) => {
const isHighlighted = type === "original" && i === BITS - 1 - bitPosition;
const isPlaced = type === "result" && i < bitPosition;
const isCurrent = type === "result" && i === bitPosition - 1;
svg.append("rect")
.attr("x", x + i * 45)
.attr("y", y)
.attr("width", 35)
.attr("height", 35)
.attr("rx", 5)
.attr("fill", isHighlighted ? "#fff3e0" :
isCurrent ? "#c8e6c9" :
isPlaced ? "#e8f5e9" :
bit === '1' ? "#e3f2fd" : "#f5f5f5")
.attr("stroke", isHighlighted ? "#f57c00" :
isCurrent ? "#4caf50" :
bit === '1' ? "#1976d2" : "#bdbdbd")
.attr("stroke-width", isHighlighted || isCurrent ? 3 : 2);
svg.append("text")
.attr("x", x + i * 45 + 17.5)
.attr("y", y + 22)
.attr("text-anchor", "middle")
.attr("font-family", "monospace")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", bit === '1' ? "#1976d2" : "#999")
.text(bit);
});
}
function step() {
if (bitPosition >= BITS) return false;
const bit = (originalNum >> bitPosition) & 1;
result |= bit << (BITS - 1 - bitPosition);
n = originalNum >> (bitPosition + 1);
document.getElementById("bitPos").textContent = bitPosition;
document.getElementById("currentBit").textContent = bit;
bitPosition++;
draw();
if (bitPosition >= BITS) {
document.getElementById("status").textContent =
`Complete! ${originalNum} → ${result} (reversed)`;
return false;
} else {
document.getElementById("status").textContent =
`Extracted bit ${bitPosition - 1} (value: ${bit}), placed at position ${BITS - bitPosition}`;
return true;
}
}
function reset() {
n = originalNum;
result = 0;
bitPosition = 0;
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("bitPos").textContent = "-";
document.getElementById("currentBit").textContent = "-";
document.getElementById("status").textContent = 'Click "Step" to reverse bits one at a time';
document.getElementById("autoBtn").textContent = "Auto Run";
draw();
}
function autoRun() {
if (autoRunning) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 2100 - document.getElementById("speed").value;
autoTimer = setInterval(() => {
if (!step()) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, speed);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
draw();
</script>
</body>
</html>