Skip to content

Commit b4bd5f1

Browse files
author
Partho Biswas
committed
415_Add_Strings
1 parent ddb0831 commit b4bd5f1

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@ I have solved quite a number of problems from several topics. See the below tabl
243243
|39| [350. Intersection of Two Arrays II](https://tinyurl.com/y9kdrubz) | [Python](https://tinyurl.com/wu6rdaw/350_Intersection_of_Two_Arrays_II.py), [Swift](https://tinyurl.com/wuja3c4/350_Intersection_of_Two_Arrays_II.swift) | --- | Easy | Check the follow-ups |
244244
|40| **[249. Group Shifted Strings](https://tinyurl.com/jsfd4l3)** | [Python](https://tinyurl.com/wu6rdaw/249_Group_Shifted_Strings.py), [Swift](https://tinyurl.com/wuja3c4/249_Group_Shifted_Strings.swift) | [Art 1](https://tinyurl.com/yd4ckev2) | Medium | Tricky one |
245245
|41| **[158. Read N Characters Given Read4 II - Call multiple times](https://tinyurl.com/y6snjozr)** | [Python](https://tinyurl.com/wu6rdaw/158_Read_N_Characters_Given_Read4_II_Call_multiple_times.py), [Swift](https://tinyurl.com/wuja3c4/158_Read_N_Characters_Given_Read4_II_Call_multiple_times.swift) | [Art 1](https://tinyurl.com/y5qu5dgz) | Hard | Good one |
246+
|42| [415. Add Strings](https://tinyurl.com/y7cbq62x) | [Python](https://tinyurl.com/wu6rdaw/415_Add_Strings.py), [Swift](https://tinyurl.com/wuja3c4/415_Add_Strings.swift) | [Art 1](https://tinyurl.com/y6v9uj9o) | Easy | --- |
246247

247248

248249
</p>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import Foundation
2+
class Solution {
3+
func addStrings(_ num1: String, _ num2: String) -> String {
4+
var digits1: [Int] = num1.compactMap { $0.wholeNumberValue }
5+
var digits2: [Int] = num2.compactMap { $0.wholeNumberValue }
6+
var carry = 0
7+
var resultStack: [Int] = []
8+
while digits1.count > 0 || digits2.count > 0 {
9+
var (digit1, digit2) = (0, 0)
10+
if digits1.count > 0 {
11+
digit1 = digits1.popLast()!
12+
}
13+
if digits2.count > 0 {
14+
digit2 = digits2.popLast()!
15+
}
16+
let sum = digit1 + digit2 + carry
17+
let remainder = sum % 10
18+
carry = sum / 10
19+
resultStack.append(remainder)
20+
}
21+
if carry > 0 {
22+
resultStack.append(carry)
23+
}
24+
resultStack = resultStack.reversed()
25+
return resultStack.reduce("", { $0 + String($1)})
26+
}
27+
}

0 commit comments

Comments
 (0)