You are given two non-empty linked lists representing two non-negative integers. Each of their numbers is stored in reverse order 2023-03-01 15:400 read · 0 likes · 0 comments

You are given two non-empty linked lists representing two non-negative integers. Each of them is stored in reverse order
2023-03-01 15:400Read· 0Like· 0Comment

Yogurt Park
Fans: 1747 Articles: 71
Followers
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.

/**

  • 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) {



    

    // Initialize variables

    ListNode result = new ListNode(0); // Head node

    ListNode prevNode = result;

    int carry = 0;

    

    while (l1 != null || l2 != null) {

        int x = (l1 != null) ? l1.val : 0;

        int y = (l2 != null) ? l2.val : 0;

        int sum = x + y + carry;

        

        // Update carry

        if (sum > 9) {

            carry = 1;

            sum %= 10;

        } else {

            carry = 0;

        }

        

        // Update the linked list

        ListNode currentNode = new ListNode(sum);

        prevNode.next = currentNode;

        prevNode = currentNode;

        

        // Move to the next nodes of l1 and l2

        if (l1 != null) {

            l1 = l1.next;

        }

        if (l2 != null) {

            l2 = l2.next;

        }

    }



    // Check if there is any carry left

    if (carry != 0) {

        prevNode.next = new ListNode(carry);

    }

    

    // Return the resulting list

    return result.next;

}

}

Guess you like

Origin blog.csdn.net/zezeaichirou/article/details/129283009