This repository was archived by the owner on Apr 27, 2025. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ # 415. Add Strings
2+
3+ ### 2017-04-05
4+
5+ Given two non-negative integers ` num1 ` and ` num2 ` represented as string, return the sum of ` num1 ` and ` num2 ` .
6+
7+ ** Note:**
8+
9+ 1 . The length of both ` num1 ` and ` num2 ` is < 5100.
10+ 2 . Both ` num1 ` and ` num2 ` contains only digits ` 0-9 ` .
11+ 3 . Both ` num1 ` and ` num2 ` does not contain any leading zero.
12+ 4 . You ** must not use any built-in BigInteger library** or ** convert the inputs to integer** directly.
13+
14+
15+
16+ # Solution
17+
18+ ``` swift
19+ class Solution {
20+ func addStrings (_ num1 : String , _ num2 : String ) -> String {
21+ func toIntArray (string : String ) -> [Int8 ] {
22+ guard var n = string.cString (using : String .Encoding .utf8 ) else { return [] }
23+ n = n.reversed ()
24+ n.removeFirst ()
25+ return n.map ({ (v : Int8 ) -> Int8 in
26+ return v - 48
27+ })
28+ }
29+
30+ let n1 = toIntArray (string : num1)
31+ let n2 = toIntArray (string : num2)
32+ let count = max (n1.count , n2.count )
33+ var n3 = [Int8 ](repeating : 0 , count : count + 1 )
34+
35+ for i in 0 ..< count {
36+ let c = (i < n1.count ? n1[i] : 0 ) + (i < n2.count ? n2[i] : 0 )
37+ n3[i] = n3[i] + c
38+ if n3[i] >= 10 {
39+ n3[i + 1 ] += n3[i] / 10
40+ n3[i] = n3[i] % 10
41+ }
42+ }
43+ if let n = n3.last , n == 0 {
44+ n3.removeLast ()
45+ }
46+
47+ if n3.count > 0 {
48+ return n3.reduce (" " , { " \( $1 ) \( $0 ) " })
49+ } else {
50+ return " 0"
51+ }
52+ }
53+ }
54+ ```
55+
You can’t perform that action at this time.
0 commit comments