-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0191_number_of_1_bits.html
More file actions
361 lines (304 loc) · 12.8 KB
/
0191_number_of_1_bits.html
File metadata and controls
361 lines (304 loc) · 12.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number of 1 Bits - LeetCode 191</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">#0191</span> Number of 1 Bits (Hamming Weight)</h1>
<p><strong>Problem:</strong> Write a function that takes an unsigned integer and returns the number of '1' bits it has.</p>
<p><strong>Pattern:</strong> Bit Manipulation - n & (n-1) clears the lowest set bit</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/0191_number_of_1s_bit/0191_number_of_1s_bit.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Bit manipulation works with <strong>binary representations</strong>:</p>
<ul>
<li><strong>AND (&):</strong> Both bits must be 1</li>
<li><strong>OR (|):</strong> At least one bit is 1</li>
<li><strong>XOR (^):</strong> Bits must be different</li>
<li><strong>Shift:</strong> Move bits left/right</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="800">
</div>
</div>
<div class="status" id="status">Click "Step" to count 1 bits using n & (n-1) trick</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Current n:</span>
<span id="currentN">-</span>
</div>
<div class="var-item">
<span class="var-label">Count:</span>
<span id="countDisplay">0</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode 191. Number of 1 Bits
Problem from LeetCode: https://leetcode.com/problems/number-of-1-bits/
Description:
Write a function that takes an unsigned integer and returns the number of '1' bits it has
(also known as the Hamming weight).
Note:
- Note that in some languages, such as Java, there is no unsigned integer type.
In this case, the input will be given as a signed integer type.
It should not affect your implementation, as the integer's internal binary representation is the same,
whether it is signed or unsigned.
- In Java, the compiler represents the signed integers using 2's complement notation.
Therefore, in Example 3, the input represents the signed integer -3.
Example 1:
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Constraints:
- The input must be a binary string of length 32.
Follow up: If this function is called many times, how would you optimize it?
"""
class Solution:
def hamming_weight(self, n: int) ->int:
"""
Returns the number of '1' bits in the binary representation of n.
This uses Brian Kernighan's algorithm:
n & (n-1) clears the least significant '1' bit in n.
We count how many times we can do this until n becomes 0.
"""
count = 0
while n != 0:
count += 1
n = n & n - 1
return count
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
n1 = 0b00000000000000000000000000001011 # 11 in decimal
result1 = solution.hamming_weight(n1)
print(f"Input: n = {bin(n1)} ({n1})")
print(f"Output: {result1}") # Expected output: 3
# Example 2
n2 = 0b00000000000000000000000010000000 # 128 in decimal
result2 = solution.hamming_weight(n2)
print(f"Input: n = {bin(n2)} ({n2})")
print(f"Output: {result2}") # Expected output: 1
# Example 3
n3 = 0b11111111111111111111111111111101 # -3 as signed 32-bit int
result3 = solution.hamming_weight(n3)
print(f"Input: n = {bin(n3)} ({n3})")
print(f"Output: {result3}") # Expected output: 31
</pre>
</div>
</div>
</div>
<script>
const BITS = 8;
const originalNum = 43; // 00101011 = 4 ones
let n = originalNum;
let count = 0;
let history = [{n: originalNum, cleared: -1}];
let autoRunning = false;
let autoTimer = null;
const width = 800;
const height = 450;
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();
svg.append("text")
.attr("x", width / 2)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Counting 1s in ${originalNum} using n & (n-1) trick`);
// Explanation
svg.append("text")
.attr("x", width / 2)
.attr("y", 55)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#666")
.text("n & (n-1) clears the rightmost 1 bit. Count how many times until n = 0");
// Show history of operations
const startY = 90;
const rowHeight = 45;
history.forEach((h, idx) => {
const y = startY + idx * rowHeight;
const bits = toBinary(h.n);
// Step label
svg.append("text")
.attr("x", 60)
.attr("y", y + 20)
.attr("text-anchor", "end")
.attr("font-size", "12px")
.attr("fill", "#666")
.text(idx === 0 ? "Start:" : `Step ${idx}:`);
// Draw bits
bits.split('').forEach((bit, bitIdx) => {
const wasCleared = h.cleared === BITS - 1 - bitIdx;
const x = 80 + bitIdx * 40;
svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", 32)
.attr("height", 32)
.attr("rx", 4)
.attr("fill", wasCleared ? "#ffcdd2" : bit === '1' ? "#c8e6c9" : "#f5f5f5")
.attr("stroke", wasCleared ? "#e53935" : bit === '1' ? "#4caf50" : "#bdbdbd")
.attr("stroke-width", wasCleared ? 3 : 2);
svg.append("text")
.attr("x", x + 16)
.attr("y", y + 20)
.attr("text-anchor", "middle")
.attr("font-family", "monospace")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", bit === '1' ? "#2e7d32" : "#999")
.text(bit);
});
// Value
svg.append("text")
.attr("x", 420)
.attr("y", y + 20)
.attr("font-size", "14px")
.text(`n = ${h.n}`);
// Arrow to next
if (idx < history.length - 1) {
svg.append("text")
.attr("x", 500)
.attr("y", y + 20)
.attr("font-size", "12px")
.attr("fill", "#666")
.text(`n & (n-1) = ${h.n} & ${h.n - 1}`);
}
});
// Count display
const countY = startY + history.length * rowHeight + 20;
svg.append("rect")
.attr("x", width / 2 - 80)
.attr("y", countY)
.attr("width", 160)
.attr("height", 50)
.attr("rx", 8)
.attr("fill", n === 0 ? "#c8e6c9" : "#e3f2fd")
.attr("stroke", n === 0 ? "#4caf50" : "#1976d2")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", width / 2)
.attr("y", countY + 32)
.attr("text-anchor", "middle")
.attr("font-size", "24px")
.attr("font-weight", "bold")
.text(`Count: ${count}`);
// Visual of which bits were originally 1
const legendY = countY + 80;
svg.append("text")
.attr("x", width / 2)
.attr("y", legendY)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("fill", "#666")
.text(`Original ${originalNum} = ${toBinary(originalNum)} has ${toBinary(originalNum).split('').filter(b => b === '1').length} ones`);
}
function findClearedBitPosition(before, after) {
const diff = before ^ after;
for (let i = 0; i < BITS; i++) {
if ((diff >> i) & 1) return i;
}
return -1;
}
function step() {
if (n === 0) return false;
const prevN = n;
n = n & (n - 1);
count++;
const clearedPos = findClearedBitPosition(prevN, n);
history.push({n: n, cleared: clearedPos});
document.getElementById("currentN").textContent = `${n} (${toBinary(n)})`;
document.getElementById("countDisplay").textContent = count;
draw();
if (n === 0) {
document.getElementById("status").textContent =
`Complete! ${originalNum} has ${count} one bits`;
return false;
} else {
document.getElementById("status").textContent =
`Cleared lowest 1 bit: ${prevN} & ${prevN - 1} = ${n}`;
return true;
}
}
function reset() {
n = originalNum;
count = 0;
history = [{n: originalNum, cleared: -1}];
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("currentN").textContent = "-";
document.getElementById("countDisplay").textContent = "0";
document.getElementById("status").textContent = 'Click "Step" to count 1 bits using n & (n-1) trick';
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>