-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd_Strings.swift
129 lines (100 loc) · 2.67 KB
/
Add_Strings.swift
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Example 1:
Input: num1 = "11", num2 = "123"
Output: "134"
Example 2:
Input: num1 = "456", num2 = "77"
Output: "533"
Example 3:
Input: num1 = "0", num2 = "0"
Output: "0"
Constraints:
1 <= num1.length, num2.length <= 104
num1 and num2 consist of only digits.
num1 and num2 don't have any leading zeros except for the zero itself.
*/
/*
Solution 2:
optimize solution 1 by only loop in one place
*/
class Solution {
func addStrings(_ num1: String, _ num2: String) -> String {
let n1 = num1.count
let n2 = num2.count
var num1 = Array(num1.reversed())
var num2 = Array(num2.reversed())
var num = [Int]()
var i = 0
var cur = 0
while i < max(n1, n2) {
if i < n1 {
cur += num1[i].wholeNumberValue!
}
if i < n2 {
cur += num2[i].wholeNumberValue!
}
num.append(cur%10)
cur /= 10
i += 1
}
if cur != 0 {
num.append(cur)
}
// reverse num and convert it to string
num.reverse()
var str = String()
for i in num {
str.append(String(i).first!)
}
return str
}
}
/*
Solution 1:
convert each num to intArr first,
then add num to intArr
then final convert intArr to string
Time Complexity: O(max(n1, n2))
Space Complexity: O(n1 + n2)
*/
class Solution {
func addStrings(_ num1: String, _ num2: String) -> String {
var num1 = num1.map { $0.wholeNumberValue! }
var num2 = num2.map { $0.wholeNumberValue! }
let n1 = num1.count
let n2 = num2.count
var i1 = n1-1
var i2 = n2-1
var addArr = [Int]()
var cur = 0
while i1 >= 0, i2 >= 0 {
cur += num1[i1] + num2[i2]
addArr.insert(cur % 10, at: 0)
cur /= 10
i1 -= 1
i2 -= 1
}
while i1 >= 0 {
cur += num1[i1]
addArr.insert(cur % 10, at: 0)
cur /= 10
i1 -= 1
}
while i2 >= 0 {
cur += num2[i2]
addArr.insert(cur % 10, at: 0)
cur /= 10
i2 -= 1
}
if cur != 0 {
addArr.insert(cur, at: 0)
}
var str = String()
for num in addArr {
str.append(String(num))
}
return str
}
}