BigInt Arbitrary Precision
Write a JavaScript function that takes two integers as strings (may exceed Number.MAX_SAFE_INTEGER), converts them to BigInt, adds them, and returns the result as a string. BigInt provides arbitrary precision for integer arithmetic beyond the 53-bit limitation of Number.
BigInt was introduced in ES2020 to address JavaScript's limitations with large integers. The Number type can only safely represent integers up to 2^53 - 1 (about 9 quadrillion). Beyond that, precision is lost. BigInt can represent arbitrarily large integers with exact precision. BigInt literals are written with an n suffix: 9007199254740993n.
BigInt operations behave like mathematical integer arithmetic: division truncates toward zero. BigInt cannot be mixed with regular Number in operations — they must be explicitly converted. The typeof a BigInt is "bigint". BigInt supports +, -, *, /, %, **, comparison operators, and bitwise operators.
Time complexity is O(n) where n is the number of digits. Space complexity is O(n). BigInt arithmetic is implemented natively and is much faster than manual string-based big number arithmetic.
Edge cases include negative BigInts, zero, very large values with hundreds of digits, and converting the result back to string for display (use .toString() without the n suffix).
Example Input & Output
Zero addition
Negative plus positive
Carry beyond safe range
Large numbers
Beyond safe integer, precise result
Algorithm Flow
Solution Approach
Perform precise integer arithmetic beyond the safe Number range using BigInt. BigInt is created by appending n to an integer literal or calling BigInt(). It supports standard arithmetic operators and can represent arbitrarily large integers.
BigInt cannot be mixed with regular numbers in arithmetic operations. Comparison operators work between BigInt and Number. Bitwise operations are supported only for BigInt operands.
Time O(1), Space O(1).
Best Answers
function solution(a, b) {
var bigA = BigInt(a);
var bigB = BigInt(b);
return (bigA + bigB).toString();
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
