-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0415_add_strings.go
More file actions
50 lines (39 loc) · 872 Bytes
/
s0415_add_strings.go
File metadata and controls
50 lines (39 loc) · 872 Bytes
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
50
/*
https://leetcode.com/problems/add-strings/
Given two non-negative integers, num1 and num2 represented as string, return
the sum
of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling
large integers
(such as BigInteger). You must also not convert the inputs to integers
directly.
*/
package solutions
func addStrings(num1, num2 string) string {
var l int
if len(num1) > len(num2) {
l = len(num1)
} else {
l = len(num2)
}
sum := make([]byte, l+1)
carry := byte(0)
for i := 0; i < l; i++ {
a, b := byte(0), byte(0)
if i < len(num1) {
a = num1[len(num1)-i-1] - '0'
}
if i < len(num2) {
b = num2[len(num2)-i-1] - '0'
}
s := a + b + carry
carry = s / 10
sum[len(sum)-i-1] = s%10 + '0'
}
if carry > 0 {
sum[0] = '1'
} else {
sum = sum[1:]
}
return string(sum)
}