Sum Big Integers

白昼怎懂夜的黑 提交于 2019-12-12 02:49:13

问题


I'm currently stuck on a Codewars challenge that I can't get my head around:

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();
}

Any help would be much appreciated.

Edit:

Fiddle example: https://jsfiddle.net/ag1z4x7d/


回答1:


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('')
   ...
}



回答2:


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>');


来源:https://stackoverflow.com/questions/36080824/sum-big-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!