-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0202_happy_number.html
More file actions
441 lines (377 loc) · 14.7 KB
/
Copy path0202_happy_number.html
File metadata and controls
441 lines (377 loc) · 14.7 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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>202 - Happy Number</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">#202</span> Happy Number</h1>
<p>
A happy number is defined by repeatedly replacing the number with the sum of
squares of its digits until it equals 1 (happy) or loops endlessly (not happy).
Use a set to detect cycles, or Floyd's cycle detection.
</p>
<div class="problem-meta">
<span class="meta-tag">🔢 Math</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0202_happy_number/0202_happy_number.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>This algorithm solves the problem <strong>step by step</strong>:</p>
<ul>
<li><strong>Understand:</strong> Parse the input data</li>
<li><strong>Process:</strong> Apply the core logic</li>
<li><strong>Optimize:</strong> Use efficient data structures</li>
<li><strong>Return:</strong> Output the computed result</li>
</ul>
</div>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="autoRunBtn" class="btn">▶ Auto Run</button>
<button id="stepBtn" class="btn btn-success">Step</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
<label style="margin-left: 20px;">
Number: <input type="number" id="inputNum" value="19" min="1" max="999" style="width: 60px;">
</label>
</div>
<div class="status" id="status">Check if 19 is a happy number</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode 202. Happy Number
Problem from LeetCode: https://leetcode.com/problems/happy-number/
Description:
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
- Starting with any positive integer, replace the number by the sum of the squares of its digits.
- Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
- Those numbers for which this process ends in 1 are happy numbers.
Return true if n is a happy number, and false if not.
Example 1:
Input: n = 19
Output: true
Explanation:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1
Example 2:
Input: n = 2
Output: false
Constraints:
- 1 <= n <= 2³¹ - 1
"""
class Solution:
def is_happy(self, n: int) ->bool:
"""
Determine if a number is "happy".
A happy number is defined by the following process:
- Starting with any positive integer, replace the number by the sum of the squares of its digits.
- Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle.
- Those numbers for which this process ends in 1 are happy numbers.
Args:
n: A positive integer
Returns:
bool: True if n is a happy number, False otherwise
"""
seen_numbers = set()
while n != 1 and n not in seen_numbers:
seen_numbers.add(n)
n = self._get_sum_of_squares(n)
return n == 1
def _get_sum_of_squares(self, n: int) ->int:
"""
Calculate the sum of squares of digits in a number.
Args:
n: A positive integer
Returns:
int: Sum of squares of digits
"""
sum_squares = 0
while n > 0:
digit = n % 10
sum_squares += digit * digit
n //= 10
return sum_squares
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
n1 = 19
result1 = solution.is_happy(n1)
print(f"Input: n = {n1}")
print(f"Output: {result1}") # Expected output: True
# Example 2
n2 = 2
result2 = solution.is_happy(n2)
print(f"Input: n = {n2}")
print(f"Output: {result2}") # Expected output: False
# Additional example
n3 = 7
result3 = solution.is_happy(n3)
print(f"Input: n = {n3}")
print(f"Output: {result3}") # Expected output: True
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 500;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
let inputNum = 19;
let current;
let history = [];
let seen = new Set();
let phase = "init";
let animationTimer = null;
let isHappy = null;
document.getElementById("inputNum").addEventListener("change", (e) => {
inputNum = parseInt(e.target.value) || 19;
reset();
});
function sumOfSquares(num) {
let total = 0;
while (num > 0) {
const digit = num % 10;
total += digit * digit;
num = Math.floor(num / 10);
}
return total;
}
function getDigits(num) {
return num.toString().split('').map(Number);
}
function reset() {
current = inputNum;
history = [current];
seen = new Set([current]);
phase = "init";
isHappy = null;
if (animationTimer) clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
document.getElementById("status").textContent = `Check if ${inputNum} is a happy number`;
render();
}
function render() {
svg.selectAll("*").remove();
// Title
svg.append("text")
.attr("x", 30)
.attr("y", 35)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(`Happy Number Check: ${inputNum}`);
// Current calculation
const calcY = 70;
const digits = getDigits(current);
svg.append("text")
.attr("x", 30)
.attr("y", calcY)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#64748b")
.text("Current:");
svg.append("rect")
.attr("x", 100)
.attr("y", calcY - 22)
.attr("width", 80)
.attr("height", 35)
.attr("rx", 8)
.attr("fill", current === 1 ? "#d1fae5" : "#fef3c7")
.attr("stroke", current === 1 ? "#10b981" : "#f59e0b")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", 140)
.attr("y", calcY + 2)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(current);
// Show calculation breakdown
if (phase !== "done") {
svg.append("text")
.attr("x", 200)
.attr("y", calcY)
.attr("font-size", "14px")
.attr("fill", "#64748b")
.text(`= ${digits.map(d => `${d}²`).join(' + ')} = ${digits.map(d => d*d).join(' + ')} = ${sumOfSquares(current)}`);
}
// History chain
const historyY = 150;
svg.append("text")
.attr("x", 30)
.attr("y", historyY)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#64748b")
.text("Sequence:");
const nodeWidth = 60;
const spacing = 80;
const startX = 30;
history.forEach((num, idx) => {
const x = startX + idx * spacing;
const y = historyY + 30;
const isLast = idx === history.length - 1;
svg.append("circle")
.attr("cx", x + nodeWidth/2)
.attr("cy", y + 20)
.attr("r", 25)
.attr("fill", num === 1 ? "#d1fae5" : isLast ? "#fef3c7" : "#e0e7ff")
.attr("stroke", num === 1 ? "#10b981" : isLast ? "#f59e0b" : "#6366f1")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", x + nodeWidth/2)
.attr("y", y + 26)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(num);
// Arrow to next
if (idx < history.length - 1) {
svg.append("line")
.attr("x1", x + nodeWidth/2 + 28)
.attr("y1", y + 20)
.attr("x2", x + spacing + nodeWidth/2 - 28)
.attr("y2", y + 20)
.attr("stroke", "#94a3b8")
.attr("stroke-width", 2)
.attr("marker-end", "url(#arrow)");
}
});
// Arrow marker
svg.append("defs")
.append("marker")
.attr("id", "arrow")
.attr("viewBox", "0 0 10 10")
.attr("refX", 9)
.attr("refY", 5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M 0 0 L 10 5 L 0 10 z")
.attr("fill", "#94a3b8");
// Seen set
const seenY = 280;
svg.append("text")
.attr("x", 30)
.attr("y", seenY)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#64748b")
.text(`Seen set: {${[...seen].join(', ')}}`);
// Algorithm explanation
svg.append("text")
.attr("x", 30)
.attr("y", 340)
.attr("font-size", "13px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Algorithm:");
const steps = [
"1. Calculate sum of squares of digits",
"2. If result is 1 → Happy number!",
"3. If result was seen before → Cycle, not happy",
"4. Otherwise, repeat with new number"
];
steps.forEach((step, i) => {
svg.append("text")
.attr("x", 30)
.attr("y", 365 + i * 22)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text(step);
});
// Result
if (phase === "done") {
const resultY = 450;
svg.append("rect")
.attr("x", 400)
.attr("y", resultY - 35)
.attr("width", 350)
.attr("height", 55)
.attr("rx", 10)
.attr("fill", isHappy ? "#d1fae5" : "#fee2e2")
.attr("stroke", isHappy ? "#10b981" : "#ef4444")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", 575)
.attr("y", resultY)
.attr("text-anchor", "middle")
.attr("font-size", "18px")
.attr("font-weight", "bold")
.attr("fill", isHappy ? "#10b981" : "#ef4444")
.text(isHappy ? `✓ ${inputNum} is a Happy Number!` : `✗ ${inputNum} is NOT Happy (cycle detected)`);
}
}
function step() {
if (phase === "done") return;
if (current === 1) {
isHappy = true;
phase = "done";
document.getElementById("status").textContent = `✓ Reached 1! ${inputNum} is a happy number!`;
render();
return;
}
const next = sumOfSquares(current);
if (seen.has(next)) {
isHappy = false;
phase = "done";
history.push(next);
document.getElementById("status").textContent = `✗ Cycle detected! ${next} was seen before. Not a happy number.`;
render();
return;
}
seen.add(next);
history.push(next);
current = next;
document.getElementById("status").textContent =
`Sum of squares: ${next}. Continuing...`;
render();
}
function autoRun() {
if (animationTimer) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
document.getElementById("autoRunBtn").textContent = "⏸ Pause";
animationTimer = setInterval(() => {
if (phase === "done") {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
step();
}, 800);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
reset();
</script>
</body>
</html>