【LeetCode】2.Add Two Numbers

1.题目描述

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

给出两个非空的链表用来表示两个非负的整数。其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

2.Solutions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class AddTwoNumbers02 {

public static void main(String[] args) {
int[] arr1 = {2,4,3};
int[] arr2 = {5,6,4};
ListNode l1 = new ListNode(arr1[0]);
ListNode l2 = new ListNode(arr2[0]);
ListNode cur = l1;
int i = 0;
while(++i<arr1.length){
cur.next = new ListNode(arr1[i]);
cur = cur.next;
}
i = 0;
cur = l2;
while(++i<arr2.length){
cur.next = new ListNode(arr2[i]);
cur = cur.next;
}
cur = addTwoNumbers(l1,l2);
while(cur != null){
System.out.print(cur.val+" ");
cur = cur.next;
}
}

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode sentinel = head;
int sum = 0;
while (l1 != null || l2 != null) {
sum /= 10;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
sentinel.next = new ListNode(sum % 10);
sentinel = sentinel.next;
}
if (sum / 10 == 1)
sentinel.next = new ListNode(1);
return head.next;
}
}

class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
(完)
谢谢你请我吃糖果!
0%