It is necessary to realize the subtraction of large numbers. Wrote function, but in console displays with error: 499999-41900

 function sub (a, b) { a = a.split('').reverse(); b = b.split('').reverse(); var index; var c = 0; var length = a.length; for (index = 0; index < length; index++) { console.log(a[index], b[index], c) if (c) { a[index] -= (b[index] || 0) + c; } else { a[index] -= (b[index] || 0); } a[index] += (c = (a[index] < 0) ? 1 : 0) * 10; } // Count the zeroes which will be removed index = 0; length = a.length - 1; while (a[length - index] === 0 && length - index > 0) { index++; } if (index > 0) { a.splice(-index); } return a.reverse().join(''); } console.log(sub('5000000002', '5102')); 

Tell me, please, what could be the error?

  • Try to describe in words what is happening in your code - Grundy
  • a [index] you have a string, like b [index] . When you add a line with something, you have the addition of lines, and '4'+0 returns '40' . For the solution, just cast the numbers to all the characters - Grundy

0