[Leetcode] Adding two numbers (adding reversed linked lists)

[Leetcode] Adding two numbers (adding reversed linked lists)

You are given two non- empty linked lists representing two non-negative integers. Each of their digits is stored in reverse order, and each node can only store one digit.
Please add two numbers and return a linked list representing the sum in the same form.
You can assume that neither number starts with a zero other than the number zero.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0 ], l2 = [0]
Output: [0]
Source: LeetCode
link: https://leetcode-cn.com/problems/add-two-numbers

code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    
        ListNode firstNode = new ListNode();
        ListNode current = firstNode;
        int carry = 0;       //表示进位
        while (l1 != null || l2 != null) {
    
    
            int sum = carry;
            if (l1 != null) {
    
    
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
    
    
                sum += l2.val;
                l2 = l2.next;
            }
            if (sum >= 10) {
    
    
                carry = 1;
                sum -= 10;
            }else{
    
    
                carry = 0;
            }
            current.next = new ListNode(sum);
            current = current.next;
        }
        if (carry == 1){
    
    
            current.next = new ListNode(1);
        }
        return firstNode.next;
    }
}

Idea:
At first, I wanted to invert the two linked lists, convert them into integers, add them directly and store them. Later, I realized that if the numbers are too large, it will be too complicated and the feasibility will be low.
Then I thought that the addition operation process is to add sequentially from the low bit to the high bit (the carry needs to be considered in the middle), then directly start from the head of the two linked lists and traverse the addition. While adding each digit, the result linked list is created until the end.

Guess you like

Origin blog.csdn.net/m2607219640/article/details/123096858