Design a BigInteger class for arithmetic on arbitrarily large integers
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: hard
Interview Round: Other
Design a data type called `BigInteger` capable of storing and performing mathematical operations on arbitrarily large integers that exceed the range of standard 64-bit types.
The class should be initialized with a string representation of an integer and support arithmetic operations (addition, subtraction, multiplication, integer division, modulo, exponentiation), comparison, absolute value, negation, and string conversion.
All arithmetic methods accept the second operand as a string and return the result as a string. They do not change the stored value; only `setValue` does. Division truncates toward zero. Modulo uses the sign of the dividend. Division or modulo by zero returns an error string. Exponentiation with a negative exponent returns an error string.
Implement the following methods:
- `add(other: str) -> str`: Add another big integer (given as a string) to the stored value and return the result as a string.
- `subtract(other: str) -> str`: Subtract another big integer from the stored value and return the result as a string.
- `multiply(other: str) -> str`: Multiply the stored value by another big integer and return the result as a string.
- `divide(other: str) -> str`: Perform integer division (truncated toward zero) by another big integer and return the result as a string. Returns an error string if dividing by zero.
- `mod(other: str) -> str`: Compute the modulo of the stored value by another big integer and return the result as a string. The result has the sign of the dividend. Returns an error string if the divisor is zero.
- `power(exponent: str) -> str`: Raise the stored value to the given exponent and return the result as a string. Returns an error string if the exponent is negative.
- `compareTo(other: str) -> int`: Compare the stored value with another big integer. Returns -1 if less, 0 if equal, 1 if greater.
- `absValue() -> str`: Return the absolute value of the stored number as a string.
- `negate() -> str`: Return the negation of the stored number as a string.
- `toString() -> str`: Return the string representation of the stored number.
- `setValue(value: str)`: Update the stored value to a new big integer given as a string.
Example 1:
```text
Input:
["BigInteger", "add", "multiply", "compareTo", "setValue", "divide", "mod", "power"]
[["99999999999999999999"], ["1"], ["99999999999999999999"], ["100000000000000000000"], ["-17"], ["5"], ["5"], ["3"]]
Output: [null, "100000000000000000000", "9999999999999999999800000000000000000001", -1, null, "-3", "-2", "-4913"]
Explanation:
big = BigInteger("99999999999999999999") # 20 nines, larger than any 64-bit integer
big.add("1") # "100000000000000000000"
big.multiply("99999999999999999999") # (10^20 - 1)^2 = 10^40 - 2 * 10^20 + 1
big.compareTo("100000000000000000000") # -1, the stored value is still 10^20 - 1
big.setValue("-17") # stores -17
big.divide("5") # "-3" (-3.4 truncated toward zero)
big.mod("5") # "-2" (-17 = -3 * 5 + -2, sign of the dividend)
big.power("3") # "-4913"
```
Example 2:
```text
Input:
["BigInteger", "negate", "absValue", "compareTo", "divide", "power"]
[["-42"], [], [], ["0"], ["0"], ["-1"]]
Output: [null, "42", "42", -1, "Error: Division by zero", "Error: Negative exponent"]
Explanation:
big = BigInteger("-42") # stores -42
big.negate() # "42"
big.absValue() # "42"
big.compareTo("0") # -1 (-42 < 0)
big.divide("0") # "Error: Division by zero"
big.power("-1") # "Error: Negative exponent"
```
```hint Representation
Keep the sign apart from the magnitude, and store the magnitude in chunks of several decimal digits with the least significant chunk first. Decide early how zero is stored so that "-0" can never be printed.
```
```hint Division
Long division brings down one chunk at a time. The hard step is finding how many times the divisor fits into the running remainder; look for a way to estimate that count from the leading chunks and then correct it.
```
```hint Signs
Python's `//` and `%` round toward negative infinity, so `-7 // 2` is -4. Work out the sign rules for truncating division and dividend-signed modulo before you reuse any built-in operator.
```
### Constraints & Assumptions
- Input numbers are valid integer strings, optionally prefixed with `-` for negative values.
- Numbers can have up to ${10^5}$ digits.
- At most ${10^4}$ operations will be called.
- Division and modulo by zero return `"Error: Division by zero"`.
- Power with a negative exponent returns `"Error: Negative exponent"`.
### Clarifying Questions to Ask
- May I use the language's built-in arbitrary-precision integer, or should the arithmetic be implemented on digit arrays?
- Can input strings carry a leading `+`, leading zeros, or `-0`, and should every output be normalized (no leading zeros, no negative zero)?
- How large can the exponent passed to `power` be? A base with ${10^5}$ digits raised to even a small exponent gives a very large result.
- What should `power` return when the stored value is 0 and the exponent is 0?
### What a Strong Answer Covers
- The internal representation (how the sign, the digits or limbs, and zero are stored) and how parsing and printing keep it normalized.
- Signed addition and subtraction built from magnitude comparison, addition and subtraction.
- Multiplication and long division on that representation, including how each quotient digit is found.
- The sign rules for truncating division and dividend-signed modulo, and the two error strings.
- The cost of each operation at ${10^5}$ digits, and when a faster multiplication algorithm or the built-in type is the better choice.
### Follow-up Questions
- Multiplying two ${10^5}$-digit numbers with the schoolbook method is slow. How would you make it faster?
- How would you add `modPow(exponent, modulus)` so that it works when the full power would have millions of digits?
- If you stored limbs in base `2^32` instead of a power of ten, what would happen to the cost of the constructor and `toString`?
- How would you make `BigInteger` immutable, and what would that mean for `setValue`?
Overview: Design a BigInteger class that stores integers too large for 64-bit types and supports addition, subtraction, multiplication, truncating division, modulo, exponentiation and comparison on decimal strings. It tests sign and magnitude handling, long division on digit arrays, and edge cases such as negative zero and division by zero.