给定两个整数的字符串表示形式,返回这些整数之和的字符串表示形式

Given the string representations of two integers, return the string representation of the sum of those integers

本文关键字:表示 整数 字符串 返回 和的 两个      更新时间:2023-09-26

例如:

sumStrings('1','2') // => '3'
C# sumStrings("1","2") // => "3"

我的代码:

function sumStrings(a,b) { 
a = Number(a);
b = Number(b); 
var total = a + b ;
return total.toString();
}

当我用以下内容尝试上面的代码时,它有一个问题。

sumStrings('712569312664357328695151392', '8100824045303269669937');

我得到 :

7.125774134884027e+26

而不是:

712577413488402631964821329 

请帮忙!

您的结果以浮点形式返回给您,因为它大于最大整数值。

我相信 javascript 中的最大 int 值是 9007199254740991。

您可以通过查看以下内容来检查限制:alert([ Number.MAX_VALUE, Number.MIN_VALUE ]);

编辑:如果你需要大整数数学而不损失精度,你需要一个类似于这样的大整数库:https://github.com/peterolson/BigInteger.js