-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathaddStrings.go
More file actions
49 lines (41 loc) · 1.05 KB
/
Copy pathaddStrings.go
File metadata and controls
49 lines (41 loc) · 1.05 KB
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
/* https://leetcode.com/problems/add-strings/#/description
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
*/
package lmath
import "bytes"
func addStrings(num1 string, num2 string) string {
m, n := len(num1), len(num2)
if m < n {
temp := num1
num1, num2 = num2, temp
t := m
m, n = n, t
}
var leadingZero bytes.Buffer
for i := 0; i < m-n; i++ {
leadingZero.WriteString("0")
}
leadingZero.WriteString(num2)
num2 = leadingZero.String()
temp := make([]rune, m, m)
carry := 0
for i := m - 1; i >= 0; i-- {
sum := carry + int(num1[i]-'0') + int(num2[i]-'0')
if sum > 9 {
carry = 1
temp[i] = rune(sum - 10 + '0')
} else {
carry = 0
temp[i] = rune(sum + '0')
}
}
if carry == 1 {
return "1" + string(temp)
}
return string(temp)
}