LeetCode刷题——两数相加
题目描述
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
提示:
每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零
AC代码
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 13 ListNode head = new ListNode(); 14 ListNode tail = head; 15 16 ListNode temp = new ListNode(); 17 18 while (l1 != null && l2 != null) { 19 int total = l1.val + l2.val + temp.val; 20 temp.val = 0; 21 ListNode p = new ListNode(); 22 if (total <= 9) { 23 p.val = total; 24 } else { 25 int reminder = total % 10; 26 int divide = total / 10; 27 p.val = reminder; 28 temp.val = divide; 29 } 30 tail.next = p; 31 tail = p; 32 33 l1 = l1.next; 34 l2 = l2.next; 35 } 36 37 while (l1 != null) { 38 int total = l1.val + temp.val; 39 temp.val = 0; 40 ListNode p = new ListNode(); 41 if (total <= 9) { 42 p.val = total; 43 } else { 44 int reminder = total % 10; 45 int divide = total / 10; 46 p.val = reminder; 47 temp.val = divide; 48 } 49 tail.next = p; 50 tail = p; 51 52 l1 = l1.next; 53 } 54 55 while (l2 != null) { 56 int total = l2.val + temp.val; 57 temp.val = 0; 58 ListNode p = new ListNode(); 59 if (total <= 9) { 60 p.val = total; 61 } else { 62 int reminder = total % 10; 63 int divide = total / 10; 64 p.val = reminder; 65 temp.val = divide; 66 } 67 tail.next = p; 68 tail = p; 69 70 l2 = l2.next; 71 } 72 73 if (temp.val != 0) { 74 tail.next = temp; 75 tail = temp; 76 } 77 78 return head.next; 79 } 80 }
Leetcode链接:https://leetcode-cn.com/problems/add-two-numbers/