【英文】两数相加

Preface

Add Two Numbers

Problem

Source Code

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com;

import java.util.ArrayList;
import java.util.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) {

// Convert the data of list1 to a string
String s1 = "";
ListNode point1 = l1;

do {
s1 += point1.val;
point1 = point1.next;
} while (point1!=null);

// Convert the data of list2 to a string
String s2 = "";
ListNode point2 = l2;

do {
s2 += point2.val;
point2 = point2.next;
} while (point2!=null);

// Find the string with the maximum length and the string with the minimum length
String max = null;
String min = null;
if (s1.length() > s2.length()) {
max = s1;
min = s2;
} else {
max = s2;
min = s1;
}

// Create an empty list to store the sum of the numbers
List<Integer> list = new ArrayList<>();
// Initialize the index of the maximum length string
int i = 0;
// Initialize the index of the minimum length string
int j = 0;
// Initialize the carry
int pre = 0;
// If the index of the long string has not exceeded the range, execute the outer loop
while (i<max.length()) {
int sum = 0;
// If the index of the short string has not exceeded the range
if (j<min.length()) {
// Add the two numbers at the same position (i and j should be equal at this point) and the carry
sum = Integer.parseInt(max.charAt(i)+"")+Integer.parseInt(min.charAt(j)+"")+pre;
} else {
// Add the number at the current position of the longer string and the carry
sum = Integer.parseInt(max.charAt(i)+"")+pre;
}
// Reset the carry to zero
pre = 0;
String ssum = String.valueOf(sum);
// Determine if the sum is a two-digit number
if (ssum.length()==2) {
// If it is a two-digit number, add the units digit to the list
list.add(Integer.parseInt(ssum.charAt(1)+""));
// At the same time, set the carry to 1
pre = 1;
} else if (ssum.length()==1) {
// If it is a one-digit number, directly add the units digit to the list
list.add(Integer.parseInt(ssum.charAt(0)+""));
}
// If there is still a carry in the last round, add the carry to the list
if (i==max.length()-1 && pre==1) {
list.add(1);
}
// Increase both indices by one in each loop
i++;
j++;
}

// Create an empty list node and store the result in it
ListNode listNode = new ListNode();
ListNode point = listNode;
for (int k = 0; k < list.size(); k++) {
point.val = list.get(k);
if (k!=list.size()-1) {
point.next = new ListNode();
point = point.next;
}
}

return listNode;

}

}

Done