求和大整数 [英] Sum Big Integers
问题描述
我目前正陷在Codewars挑战中,我无法理解:
I'm currently stuck on a Codewars challenge that I can't get my head around:
给出两个整数的字符串表示形式,返回这些整数的字符串表示形式,例如sumStrings('1','2') // => '3'
Given a string representation of two integers, return the string representation of those integers, e.g. sumStrings('1','2') // => '3'
到目前为止,我已使用以下代码,但由于将数字转换为科学计数法,因此在大量测试用例中均失败:
I've used the following code so far, but it fails on large number test cases as the number is converted into a scientific notation:
function sumStrings(a,b) {
var res = +a + +b;
return res.toString();
}
任何帮助将不胜感激.
小提琴示例: https://jsfiddle.net/ag1z4x7d/
推荐答案
问题是在特定的kata(IIRC)中,对于常规的32位整数,存储在a
和b
中的数字太大,和浮点运算是不精确的.因此,您的版本没有返回正确的值:
The problem is that in that specific kata (IIRC), the numbers stored in a
and b
are too large for a regular 32 bit integer, and floating point arithmetic isn't exact. Therefore, your version does not return the correct value:
sumStrings('100000000000000000000', '1')
// returns '100000000000000000000' instead of '100000000000000000001'
您必须确保不会发生这种情况.一种方法是进行良好的老式基于进位的加法,并在整个计算过程中始终停留在基于数字/字符的世界中:
You have to make sure that this does not happen. One way is to do an good old-fashioned carry-based addition and stay in the digit/character based world throughout the whole computation:
function sumStrings(a, b) {
var digits_a = a.split('')
var digits_b = b.split('')
...
}
这篇关于求和大整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!