Skip to content

Commit a00868e

Browse files
committed
commit solution 415
1 parent 3d62b4a commit a00868e

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# [415. 字符串相加](https://leetcode-cn.com/problems/add-strings/description/)
2+
3+
4+
### 题目描述
5+
6+
<p>给定两个字符串形式的非负整数&nbsp;<code>num1</code> 和<code>num2</code>&nbsp;,计算它们的和。</p>
7+
8+
<p><strong>注意:</strong></p>
9+
10+
<ol>
11+
<li><code>num1</code> 和<code>num2</code>&nbsp;的长度都小于 5100.</li>
12+
<li><code>num1</code> 和<code>num2</code> 都只包含数字&nbsp;<code>0-9</code>.</li>
13+
<li><code>num1</code> 和<code>num2</code> 都不包含任何前导零。</li>
14+
<li><strong>你不能使用任何內建 BigInteger 库,&nbsp;也不能直接将输入的字符串转换为整数形式。</strong></li>
15+
</ol>
16+
17+
### 解题思路
18+
19+
20+
### 代码实现
21+
22+
23+
#### **Golang**
24+
```go
25+
func addStrings(num1 string, num2 string) string {
26+
add := 0
27+
ans := ""
28+
for i, j := len(num1) - 1, len(num2) - 1; i >= 0 || j >= 0 || add != 0; i, j = i - 1, j - 1 {
29+
var x, y int
30+
if i >= 0 {
31+
x = int(num1[i] - '0')
32+
}
33+
if j >= 0 {
34+
y = int(num2[j] - '0')
35+
}
36+
result := x + y + add
37+
ans = strconv.Itoa(result%10) + ans
38+
add = result / 10
39+
}
40+
return ans
41+
}
42+
```
43+
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* @lc app=leetcode.cn id=415 lang=golang
3+
*
4+
* [415] 字符串相加
5+
*/
6+
7+
// @lc code=start
8+
func addStrings(num1 string, num2 string) string {
9+
add := 0
10+
ans := ""
11+
for i, j := len(num1) - 1, len(num2) - 1; i >= 0 || j >= 0 || add != 0; i, j = i - 1, j - 1 {
12+
var x, y int
13+
if i >= 0 {
14+
x = int(num1[i] - '0')
15+
}
16+
if j >= 0 {
17+
y = int(num2[j] - '0')
18+
}
19+
result := x + y + add
20+
ans = strconv.Itoa(result%10) + ans
21+
add = result / 10
22+
}
23+
return ans
24+
}
25+
// @lc code=end
26+

0 commit comments

Comments
 (0)