惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
博客园 - 叶小钗
The Cloudflare Blog
D
DataBreaches.Net
J
Java Code Geeks
G
Google Developers Blog
L
LangChain Blog
N
Netflix TechBlog - Medium
Stack Overflow Blog
Stack Overflow Blog
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
小众软件
小众软件
量子位
Apple Machine Learning Research
Apple Machine Learning Research
P
Proofpoint News Feed
博客园_首页
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
腾讯CDC

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Add Two Numbers — LeetCode #2 (Medium)
Shubham Gupt · 2026-05-18 · via DEV Community

The Problem

Add two numbers whose digits are stored as nodes of two linked lists in reverse order, and return the sum as a linked list.

Example

Input: l1 = [2,4,3], l2 = [5,6,4]

Output: [7,0,8]

342 + 465 = 807.

Constraints

  • Each list has 1 to 100 nodes
  • Each node value is a single digit, 0 to 9
  • No leading zeros except the number 0 itself

The Key Insight

Now think about how you'd add by hand. You don't glue the digits into one number first. You go column by column. So what if we do exactly that here? Take the two matching digits, add just those, write down one result, and move on.

That's the move. Column-by-column addition. And since the digits are already reversed, the ones column comes first. That lines up perfectly. One catch. Four plus six is ten. Ten doesn't fit in a single digit slot, so we keep the last digit and carry the one forward.

That carry is the only memory we need. It's just one small number, handed from each column to the next one. Watch out for one mistake. You might think to stop once both lists run out. But if the last column carried a one, you still owe one more digit.

Why It Works

Notice what we never did. We never built those big numbers. Each digit got touched once, and the carry held the only memory we needed.

Walking Through It

Let's run it. Carry starts at zero. We also keep a fake starting node, so attaching the very first digit needs no special handling. First column. Two plus five is seven, plus a carry of zero. Nothing spills over, so we attach a node holding seven.

Next column. Four plus six is ten. Ten won't fit in one digit slot, so something has to give. We keep the last digit, which is zero, and attach a node holding zero. The leftover one becomes the carry into the next column.

Last column. Three plus four is seven, plus the carried one, that makes eight. We attach a node holding eight. Both lists are empty now, and the carry is zero. There's nothing left to add, so we stop.

Drop the fake node, and the answer starts at seven. Read it out as a whole, eight hundred seven. Correct.

Complexity

We walk each list one time, so the time grows with the longer list. The answer holds one node per digit, so the memory grows the same way.

The Code

Same logic, now in Python. We make a fake starting node, a pointer to build from, and set the carry to zero. The loop keeps running while either list still has a digit, or there's a leftover carry. That last part catches the final one.

Inside, we read each digit. If a list has already run out, we treat its digit as zero, so two different lengths just work. We add the two digits and the carry. The new carry is whatever spilled past ten, and the new node takes the last digit.

Then we step all the pointers forward. When the loop ends, we hand back the list that starts right after the fake node.

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        dummy = ListNode()
        curr = dummy
        carry = 0
        while l1 or l2 or carry:
            x = l1.val if l1 else 0
            y = l2.val if l2 else 0
            total = x + y + carry
            carry = total // 10
            curr.next = ListNode(total % 10)
            curr = curr.next
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return dummy.next

Enter fullscreen mode Exit fullscreen mode

Wrap-up

And that's it. Column by column, carry the one. It's the same addition you learned in grade school, just walking a list.


📺 Watch the full walkthrough on YouTube: https://youtu.be/wz9Dhg5LYqI