Leek-Add Two Numbers

add two numbers

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:
insert image description here
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]
Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

hint:

The number of nodes in each linked list is in the range [1, 100]
0 <= Node.val <= 9
Title data guarantee that the number represented by the list does not contain leading zeros

answer:

Solution one:

class Solution {
    
    
	public ListNode addTwoNumbers(ListNode listNode1, ListNode listNode2) {
    
    
		ListNode head = null;
		ListNode tail = null;
		int carry = 0;
		while(listNode1 != null || listNode2 != null) {
    
    
			int n1 = listNode1 != null ? listNode1.val : 0;
			int n2 = listNode2 != null ? listNode2.val : 0;
			int sum = n1 + n2 + carry;
			if (head == null) {
    
    
				ListNode pre = new ListNode(sum % 10);
				head = tail = pre;
			} else {
    
    
				tail.next = new ListNode(sum % 10);
				tail = tail.next;
			}
			carry = sum / 10;
			if(listNode1 != null) {
    
    
				listNode1 = listNode1.next;
			}
			if(listNode2 != null) {
    
    
				listNode2 = listNode2.next;
			}
		}
		if(carry > 0) {
    
    
			tail.next = new ListNode(carry);	
		}
        return head;
	}
}

Solution two:

class Solution {
    
    
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
    
		ListNode node = new ListNode(0);
		ListNode preNode = node;
		int carry = 0;
		int sum = 0;
		while(l1 !=null || l2 != null || carry != 0) {
    
    
			sum = carry;
			if(l1 != null) {
    
    
				sum = sum + l1.val;
				l1 = l1.next;
			}
			if(l2 != null) {
    
    
				sum = sum + l2.val;
				l2 = l2.next;
			}
			ListNode node1 = new ListNode(sum % 10);
			preNode.next = node1;
			preNode = preNode.next;
			carry = sum / 10;
		}
        return node.next;
	}
}

I am amnesia, a funny and humorous man.

If there are any problems in the article, you can point out in the message. If you liked this article, don't forget to upvote it. WeChat official account search 失忆老幺, in addition to technology and life sharing, come and pay attention.
insert image description here

Guess you like

Origin blog.csdn.net/qq_42216791/article/details/125642786