-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0371_sum_of_two_integers.html
More file actions
404 lines (339 loc) · 13.9 KB
/
0371_sum_of_two_integers.html
File metadata and controls
404 lines (339 loc) · 13.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum of Two Integers - LeetCode 371</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">#0371</span> Sum of Two Integers</h1>
<p><strong>Problem:</strong> Given two integers a and b, return the sum of the two integers without using the operators + and -.</p>
<p><strong>Pattern:</strong> Bit Manipulation - XOR for sum without carry, AND + shift for carry</p>
<div class="problem-meta">
<span class="meta-tag">📊 Array</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0371_sum_of_two_integers/0371_sum_of_two_integers.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>
<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 add numbers using bit manipulation</div>
<div class="variables">
<div class="var-item">
<span class="var-label">a (sum without carry):</span>
<span id="aDisplay">5</span>
</div>
<div class="var-item">
<span class="var-label">b (carry):</span>
<span id="bDisplay">3</span>
</div>
<div class="var-item">
<span class="var-label">Iteration:</span>
<span id="iterDisplay">0</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Sum Of Two Integers
Problem from LeetCode: https://leetcode.com/problems/sum-of-two-integers/
Description:
Given two integers a and b, return the sum of the two integers without using the + and - operators.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = 2, b = 3
Output: 5
Constraints:
-1000 <= a, b <= 1000
"""
class Solution:
def get_sum(self, a: int, b: int) ->int:
"""
Calculate the sum of two integers a and b without using the + and - operators.
Args:
a: First integer
b: Second integer
Returns:
int: Sum of a and b
"""
mask = 4294967295
while b != 0:
temp = (a ^ b) & mask
carry = (a & b) << 1 & mask
a = temp
b = carry
if a > mask // 2:
return ~(a ^ mask)
return a
def get_sum_recursive(self, a: int, b: int) ->int:
"""
Calculate the sum using a recursive approach.
Args:
a: First integer
b: Second integer
Returns:
int: Sum of a and b
"""
mask = 4294967295
if b == 0:
if a > mask // 2:
return ~(a ^ mask)
return a
sum_without_carry = (a ^ b) & mask
carry = (a & b) << 1 & mask
return self.get_sum_recursive(sum_without_carry, carry)
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
a1, b1 = 1, 2
result1 = solution.get_sum(a1, b1)
print(f"Example 1: {a1} + {b1} = {result1}") # Expected output: 3
# Example 2
a2, b2 = 2, 3
result2 = solution.get_sum(a2, b2)
print(f"Example 2: {a2} + {b2} = {result2}") # Expected output: 5
# Example 3 - with negative numbers
a3, b3 = -1, 1
result3 = solution.get_sum(a3, b3)
print(f"Example 3: {a3} + {b3} = {result3}") # Expected output: 0
# Recursive approach
print("\nRecursive approach:")
result4 = solution.get_sum_recursive(a1, b1)
print(f"Example 1: {a1} + {b1} = {result4}") # Expected output: 3
</pre>
</div>
</div>
</div>
<script>
const BITS = 8;
const originalA = 5;
const originalB = 3;
let a = originalA;
let b = originalB;
let iteration = 0;
let autoRunning = false;
let autoTimer = null;
const width = 850;
const height = 450;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
function toBinary(num, bits = BITS) {
if (num < 0) num = (1 << bits) + num;
return (num >>> 0).toString(2).padStart(bits, '0');
}
function draw() {
svg.selectAll("*").remove();
svg.append("text")
.attr("x", width / 2)
.attr("y", 25)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Adding ${originalA} + ${originalB} without + operator`);
const startY = 60;
const colWidth = 35;
const rowHeight = 40;
// Current state
drawSection("Current a (XOR result)", toBinary(a), a, 80, startY, "#e3f2fd", "#1976d2");
drawSection("Current b (Carry)", toBinary(b), b, 80, startY + 60, "#fff3e0", "#f57c00");
if (b !== 0) {
// Show XOR operation
const xorY = startY + 140;
svg.append("text")
.attr("x", 50)
.attr("y", xorY)
.attr("font-weight", "bold")
.attr("fill", "#1976d2")
.text("XOR (sum without carry):");
drawBits(toBinary(a), 280, xorY - 20, "#e3f2fd", "#1976d2");
svg.append("text").attr("x", 240).attr("y", xorY).text("a:");
drawBits(toBinary(b), 280, xorY + 20, "#fff3e0", "#f57c00");
svg.append("text").attr("x", 230).attr("y", xorY + 40).text("⊕ b:");
svg.append("line")
.attr("x1", 280).attr("y1", xorY + 45)
.attr("x2", 280 + BITS * colWidth).attr("y2", xorY + 45)
.attr("stroke", "#333").attr("stroke-width", 2);
const xorResult = a ^ b;
drawBits(toBinary(xorResult), 280, xorY + 60, "#c8e6c9", "#4caf50");
svg.append("text")
.attr("x", 280 + BITS * colWidth + 10)
.attr("y", xorY + 80)
.attr("fill", "#4caf50")
.text(`= ${xorResult}`);
// Show AND + shift operation
const andY = startY + 280;
svg.append("text")
.attr("x", 50)
.attr("y", andY)
.attr("font-weight", "bold")
.attr("fill", "#f57c00")
.text("AND << 1 (carry):");
drawBits(toBinary(a), 280, andY - 20, "#e3f2fd", "#1976d2");
svg.append("text").attr("x", 240).attr("y", andY).text("a:");
drawBits(toBinary(b), 280, andY + 20, "#fff3e0", "#f57c00");
svg.append("text").attr("x", 230).attr("y", andY + 40).text("& b:");
svg.append("line")
.attr("x1", 280).attr("y1", andY + 45)
.attr("x2", 280 + BITS * colWidth).attr("y2", andY + 45)
.attr("stroke", "#333").attr("stroke-width", 2);
const andResult = a & b;
const carry = andResult << 1;
drawBits(toBinary(andResult), 280, andY + 60, "#e0e0e0", "#666");
svg.append("text")
.attr("x", 280 + BITS * colWidth + 10)
.attr("y", andY + 80)
.attr("fill", "#666")
.text(`= ${andResult}`);
svg.append("text")
.attr("x", 280 + BITS * colWidth + 80)
.attr("y", andY + 80)
.attr("fill", "#f57c00")
.text(`<< 1 = ${carry}`);
}
// Result
if (b === 0) {
svg.append("rect")
.attr("x", width / 2 - 100)
.attr("y", height - 80)
.attr("width", 200)
.attr("height", 50)
.attr("rx", 8)
.attr("fill", "#c8e6c9")
.attr("stroke", "#4caf50")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", width / 2)
.attr("y", height - 50)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.text(`Result: ${a}`);
}
}
function drawSection(label, binary, value, x, y, fill, stroke) {
svg.append("text")
.attr("x", x)
.attr("y", y)
.attr("font-size", "14px")
.attr("fill", "#666")
.text(label);
drawBits(binary, x + 200, y - 15, fill, stroke);
svg.append("text")
.attr("x", x + 200 + BITS * 35 + 10)
.attr("y", y)
.attr("font-weight", "bold")
.text(`= ${value}`);
}
function drawBits(bits, x, y, fill, stroke) {
bits.split('').forEach((bit, i) => {
svg.append("rect")
.attr("x", x + i * 35)
.attr("y", y)
.attr("width", 30)
.attr("height", 30)
.attr("rx", 4)
.attr("fill", bit === '1' ? fill : "#f5f5f5")
.attr("stroke", bit === '1' ? stroke : "#bdbdbd")
.attr("stroke-width", 2);
svg.append("text")
.attr("x", x + i * 35 + 15)
.attr("y", y + 20)
.attr("text-anchor", "middle")
.attr("font-family", "monospace")
.attr("font-weight", "bold")
.attr("fill", bit === '1' ? stroke : "#999")
.text(bit);
});
}
function step() {
if (b === 0) return false;
const temp = a ^ b;
b = (a & b) << 1;
a = temp;
iteration++;
document.getElementById("aDisplay").textContent = `${a} (${toBinary(a)})`;
document.getElementById("bDisplay").textContent = `${b} (${toBinary(b)})`;
document.getElementById("iterDisplay").textContent = iteration;
draw();
if (b === 0) {
document.getElementById("status").textContent =
`Complete! ${originalA} + ${originalB} = ${a}`;
return false;
} else {
document.getElementById("status").textContent =
`Iteration ${iteration}: a = ${a}, carry b = ${b}`;
return true;
}
}
function reset() {
a = originalA;
b = originalB;
iteration = 0;
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("aDisplay").textContent = `${a}`;
document.getElementById("bDisplay").textContent = `${b}`;
document.getElementById("iterDisplay").textContent = "0";
document.getElementById("status").textContent = 'Click "Step" to add numbers using bit manipulation';
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>