Add Decimal Strings Exactly
Problem statement
Two decimal numbers are supplied as strings a and b. Return their exact sum as a decimal string. Do not use eval or convert either operand to a floating-point number before adding.
For this exercise, assume both operands are nonnegative decimal strings with one or more integer digits and an optional decimal point followed by one or more fractional digits. Signs, exponent notation and whitespace are outside scope; leading and trailing zeroes are allowed.
For this exercise, return the canonical decimal representation: remove redundant leading integer zeroes and trailing fractional zeroes; omit the decimal point when no fractional digits remain. Retain one integer zero for values below one, and return 0 for an exact zero.
Function
addDecimal(a: String, b: String) → StringExamples
Example 1
a = "1.00000000012"b = "22222.1"return = "22223.10000000012"The reported example needs all eleven fractional places to remain exact.
Example 2
a = "009.0090"b = "00.991"return = "10"Fractional carry reaches the integer part; redundant zeroes are removed.
Example 3
a = "0.001"b = "7"return = "7.001"An integer operand has an implicit zero fractional part.
Constraints
- For this exercise, assume
1 <= a.length,b.length <= 10000. - Each operand follows the stated nonnegative decimal format.
- The result must remain exact even when it cannot fit in a fixed-width integer or floating-point type.