Doing arithmetic with big numbers is impossible to do with regular integer types. In JavaScript (which represents numbers as 64-bit floats), anything beyond 2^53-1 becomes increasingly less accurate.
Write a two functions (bigAdd
and bigSub
) to accurately represent these large integers as strings. They will both take two arguments: either a valid representation of an integer as a string, or a regular number. They will return the correct answer as a string. bigAdd
will sum, bigSub
will subtract.
For example:
bigAdd(1, "123456789012345678901234567890") === "123456789012345678901234567891";
bigSub("123456789012345678901234567890", 1) === "123456789012345678901234567889";
Remember, the values could be negative, and so the calculations should be made accordingly.
bigAdd(-1, "123456789012345678901234567890") === "123456789012345678901234567889";
bigSub("123456789012345678901234567890", -1) === "123456789012345678901234567891";
Tests
bigAdd(1, "123456789012345678901234567890")
bigAdd(-1, "123456789012345678901234567890")
bigSub("123456789012345678901234567890", 1)
bigSub("123456789012345678901234567890", -1)
This challenge comes from wthit56 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (4)
Thankfully, Ruby automatically converts ints to Bignums when it detects an overflow, so the Ruby solution is as simple as:
In JavaScript.
Haskell
It isn't feaaible/doesn't make sense to define similar methods that take various combinations of strings and integers. Especially in a language with support for literals of arbitrarily sized integers.
Java :)
import java.math.BigInteger;
public class BigArithmetic {
}