Skip to content

Commit db0bf00

Browse files
committed
Add Two Numbers
1 parent 43081e8 commit db0bf00

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Add Two Numbers
3+
4+
Tag: Linked List、 Math
5+
6+
https://leetcode.com/problems/add-two-numbers/description/
7+
*/
8+
9+
public class ListNode {
10+
public var val: Int
11+
public var next: ListNode?
12+
13+
public init(_ val: Int) {
14+
self.val = val
15+
self.next = nil
16+
}
17+
}
18+
19+
/**
20+
思路: 按位加, 处理好满10进1位即可
21+
*/
22+
class Solution {
23+
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
24+
var listHead: ListNode?
25+
var addOneNext = false // 下一位进1
26+
var listLastNode: ListNode?
27+
var n1: ListNode? = l1
28+
var n2: ListNode? = l2
29+
while n1 != nil || n2 != nil {
30+
let d1 = n1 != nil ? n1!.val : 0
31+
let d2 = n2 != nil ? n2!.val : 0
32+
var digitSum = d1 + d2 + (addOneNext ? 1 : 0) // 对应位置两数相加, 以及进位1
33+
if n1 != nil {
34+
n1 = n1!.next
35+
}
36+
if n2 != nil {
37+
n2 = n2!.next
38+
}
39+
addOneNext = digitSum >= 10 // 两数相加大于10, 标记下一位进1
40+
digitSum %= 10
41+
if let lastNode = listLastNode {
42+
lastNode.next = ListNode(digitSum)
43+
listLastNode = lastNode.next
44+
}
45+
else { // 头节点
46+
listHead = ListNode(digitSum)
47+
listLastNode = listHead
48+
}
49+
}
50+
if (addOneNext) { // 相同长度的两个单向链表 最后位置节点 满10进1
51+
listLastNode!.next = ListNode(1)
52+
}
53+
return listHead
54+
}
55+
}
56+
57+
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)