字符串相加
题目
官解 - 惯例解法
func addStrings(num1 string, num2 string) string {
add := 0
ans := ""
for i, j := len(num1) - 1, len(num2) - 1; i >= 0 || j >= 0 || add != 0; i, j = i - 1, j - 1 {
var x, y int
if i >= 0 {x = int(num1[i] - '0')
}
if j >= 0 {y = int(num2[j] - '0')
}
result := x + y + add
ans = strconv.Itoa(result%10) + ans
add = result / 10
}
return ans
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/add-strings/solution/zi-fu-chuan-xiang-jia-by-leetcode-solution/
起源:力扣(LeetCode)著作权归作者所有。商业转载请分割作者取得受权,非商业转载请注明出处。
成果
字符数组结构字符串
func addStrings(num1 string, num2 string) string {l1 := len(num1)
l2 := len(num2)
l := l1
if l < l2 {l = l2}
add := 0
r := make([]byte, l+1, l+1)
for i := l - 1; i >= 0; i-- {i1 := i - (l - l1)
i2 := i - (l - l2)
a := 0
b := 0
if i1 >= 0 {a = int(num1[i1] - '0')
}
if i2 >= 0 {b = int(num2[i2] - '0')
}
r[i+1] = byte(((a+b+add) % 10) + '0')
add = (a+b+add) / 10
}
if add == 0 {return string(r[1:])
}
r[0] = '1'
return string(r)
}
作者:import-7e
链接:https://leetcode-cn.com/problems/add-strings/solution/100-by-import-7e-esby/
起源:力扣(LeetCode)著作权归作者所有。商业转载请分割作者取得受权,非商业转载请注明出处。
成果
// 略微有点取巧
附上两篇对字符串拼接有参考价值的博客
https://www.jianshu.com/p/7cc…
https://hermanschaaf.com/effi…
字符串相乘
取出字符别离相乘
建一个 int 数组,按权值存储每次相乘的后果
再将其转换为字符串
func multiply(num1 string, num2 string) string {
if num1 == "0" || num2 == "0" {return "0"}
m, n := len(num1), len(num2)
ansArr := make([]int, m + n)
for i := m - 1; i >= 0; i-- {x := int(num1[i]) - '0'
for j := n - 1; j >= 0; j-- {y := int(num2[j] - '0')
ansArr[i + j + 1] += x * y
}
}
for i := m + n - 1; i > 0; i-- {ansArr[i - 1] += ansArr[i] / 10
ansArr[i] %= 10
}
ans := ""
idx := 0
if ansArr[0] == 0 {idx = 1}
for ; idx < m + n; idx++ {ans += strconv.Itoa(ansArr[idx])
}
return ans
}
成果