Golang
// 求2个很大数之和
func maxNumSum(a string, b string) string {
size := 0
alen := len(a)
blen := len(b)
if alen > blen {
size = alen
} else {
size = blen
}
result := ""
for i := 0; i < size; i++ {
// 如果下标越界了,就设置为0
num1 := 0
if i < alen {
// a[i]类型为byte(ascii码),和整型运算会报错,转换成对应整型就-48
num1 = int(a[i]) - 48
}
num2 := 0
if i < blen {
num2 = int(b[i]) - 48
}
// 字符和整型相加会报错,string(num1+num2)会变成空字符,用Sprintf或strconv.Itoa
result += fmt.Sprintf("%d", (num1 + num2))
}
return result
}
Nodejs
// 求2个很大数之和
function maxNumSum(a, b) {
const alen = a.length;
const blen = b.length;
const len = alen > blen ? alen : blen;
let result = "";
for (let i=0; i<len; i++) {
// a[i]为对应字符,转换成整型才能相加,不然变成字符累加
const num1 = i < alen ? parseInt(a[i], 10) : 0;
const num2 = i < blen ? parseInt(b[i], 10) : 0;
// 字符和整型可以相加,自动转换成字符
result += (num1 + num2)
}
return result;
}
Python
// 求2个很大数之和
def maxNumSum(a, b):
alen = len(a)
blen = len(b)
size = alen if alen > blen else blen
result = ""
for i in range(size):
// a[i]为对应字符,转换成整型才能相加,不然变成字符累加
num1 = int(a[i]) if i < alen else 0
num2 = int(b[i]) if i < blen else 0
// 字符不能和整型直接累加,需要str转换成字符
result += str(num1 + num2)
return result
C#
// 求2个很大数之和
public static string maxNumSum(string a, string b) {
int alen = a.Length;
int blen = b.Length;
int len = alen > blen ? alen : blen;
string result = "";
for (int i=0; i<len; i++) {
// Console.WriteLine(a[i].GetType());
// a[i]为char类型(ascii码),转换成对应整型-48,char可以直接和整型运算
int num1 = i < alen ? a[i] - 48 : 0;
int num2 = i < blen ? b[i] - 48 : 0;
// 字符和整型可以相加,自动转换成字符
result += (num1 + num2);
}
return result;
}
标签:string,num2,int,常见,alen,算法,result,blen
From: https://www.cnblogs.com/fanyang1/p/16630592.html