【问题标题】:Sum Big Integers对大整数求和
【发布时间】:2016-03-18 09:35:52
【问题描述】:

我目前陷入了无法理解的 Codewars 挑战:

给定两个整数的字符串表示,返回这些整数的字符串表示,例如sumStrings('1','2') // => '3'

到目前为止,我已经使用了以下代码,但它在大量测试用例中失败,因为数字被转换为科学计数法:

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

任何帮助将不胜感激。

编辑:

小提琴示例:https://jsfiddle.net/ag1z4x7d/

【问题讨论】:

标签: javascript integer scientific-notation


【解决方案1】:

function sumStrings(a, b) {                                    // sum for any length
    function carry(value, index) {                             // cash & carry
        if (!value) {                                          // no value no fun
            return;                                            // leave shop
        }
        this[index] = (this[index] || 0) + value;              // add value
        if (this[index] > 9) {                                 // carry necessary?
            carry.bind(this)(this[index] / 10 | 0, index + 1); // better know this & go on
            this[index] %= 10;                                 // remind me later
        }
    }

    var array1 = a.split('').map(Number).reverse(),            // split stuff and reverse
        array2 = b.split('').map(Number).reverse();            // here as well

    array1.forEach(carry, array2);                             // loop baby, shop every item
    return array2.reverse().join('');                          // return right ordered sum
}

document.write(sumStrings('999', '9') + '<br>');
document.write(sumStrings('9', '999') + '<br>');
document.write(sumStrings('1', '9999999999999999999999999999999999999999999999999999') + '<br>');

【讨论】:

    【解决方案2】:

    问题在于,在特定的 kata (IIRC) 中,存储在 ab 中的数字对于常规的 32 位整数来说太大了,并且浮点运算并不精确。因此,您的版本没有返回正确的值:

    sumStrings('100000000000000000000', '1')
    // returns '100000000000000000000' instead of '100000000000000000001'
    

    您必须确保不会发生这种情况。一种方法是进行良好的老式基于进位的加法,并在整个计算过程中停留在基于数字/字符的世界中:

    function sumStrings(a, b) {
       var digits_a = a.split('')
       var digits_b = b.split('')
       ...
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      相关资源
      最近更新 更多