2. Add Two Numbers | LeetCode | Top Interview 150 | Coding Questions

Published: (February 16, 2026 at 03:02 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

https://leetcode.com/problems/add-two-numbers/

Detailed Step-by-Step Explanation

https://leetcode.com/problems/add-two-numbers/solutions/7584850/beats-200-all-languages-using-linkedlist-nf53

leetcode 2

Solution

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode result = new ListNode(0);
        ListNode ptr = result;
        int carry = 0;

        while (l1 != null || l2 != null) {
            int sum = 0 + carry;

            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }

            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }

            carry = sum / 10;
            sum = sum % 10;
            ptr.next = new ListNode(sum);
            ptr = ptr.next;
        }

        if (carry == 1) ptr.next = new ListNode(1);
        return result.next;
    }
}
0 views
Back to Blog

Related posts

Read more »

Leetcode 696 Solution Explained

!pichttps://media2.dev.to/dynamic/image/width=256,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farti...