Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commitcd743be

Browse files
committed
415. Add Strings
1 parent20bbf4f commitcd743be

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎415. Add Strings.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
classSolution {
20+
funcaddStrings(_num1:String,_num2:String)->String {
21+
functoIntArray(string:String)-> [Int8] {
22+
guardvar n= string.cString(using:String.Encoding.utf8)else {return [] }
23+
n= n.reversed()
24+
n.removeFirst()
25+
return n.map({ (v:Int8)->Int8in
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 iin0..<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+
iflet 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+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp