-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
--- | ||
title: LeetCode 0002 - Add two numbers (Swift) | ||
tags: ['Algorithm'] | ||
--- | ||
|
||
[문제 링크](https://leetcode.com/problems/add-two-numbers/description/) | ||
|
||
## 문제 설명 | ||
|
||
1. single linked list 로직 | ||
2. Int형으로 환산하면 노드가 100개 연결될 수 있으므로 비트가 커버 못함 | ||
3. 노드끼리 합 연산 진행 후 carry를 뒤의 Next로 넘겨주는 로직 구현 필요 | ||
|
||
```swift | ||
/** | ||
* Definition for singly-linked list. | ||
* public class ListNode { | ||
* public var val: Int | ||
* public var next: ListNode? | ||
* public init() { self.val = 0; self.next = nil; } | ||
* public init(_ val: Int) { self.val = val; self.next = nil; } | ||
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } | ||
* } | ||
*/ | ||
class Solution { | ||
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { | ||
var l1Node = l1 | ||
var l2Node = l2 | ||
var resultNode: ListNode? = nil | ||
var nodes: [ListNode?] = [] | ||
|
||
while(l1Node != nil || l2Node != nil) { | ||
let sum = (l1Node?.val ?? 0) + (l2Node?.val ?? 0) | ||
|
||
if sum >= 10 { | ||
if let l1NodeNext = l1Node?.next { | ||
l1NodeNext.val += 1 | ||
} else if let l2NodeNext = l2Node?.next { | ||
l2NodeNext.val += 1 | ||
} else { | ||
if l1Node?.val ?? 0 >= 10 { | ||
l1Node?.next = ListNode(1) | ||
} else if l2Node?.val ?? 0 >= 10 { | ||
l2Node?.next = ListNode(1) | ||
} else { | ||
l1Node?.next = ListNode(1) | ||
} | ||
} | ||
resultNode = ListNode(sum % 10) | ||
} else { | ||
resultNode = ListNode(sum) | ||
} | ||
nodes.append(resultNode) | ||
l1Node = l1Node?.next | ||
l2Node = l2Node?.next | ||
} | ||
for index in 0..<nodes.count-1 { | ||
nodes[index]?.next = nodes[index + 1] | ||
} | ||
|
||
return nodes.first! | ||
} | ||
} | ||
``` |