TopcoderArchive
Archive
Algorithm problem

PolynomialAdder

Problem statement, definition, constraints, and public examples.

Problem Statement

A polynomial is the sum of a number of terms of the form "ax^b", where no two terms have the same value of b. However, when b is equal to 0, the "x^b" part of the term is omitted, and when b is equal to 1, the "^b" part is omitted ("5x^2+4x+3", for instance). Furthermore, if a is equal to 1, then it is omitted, unless b is equal to 0. If a is equal to 0, then the entire term is omitted, unless all of the terms in the polynomial have a=0, in which case the polynomial should simply be "0". Finally, some of the terms may be subtracted instead of added, and the terms must be sorted by descending order of b. Hence the following are all valid polynomials:
0
1
-1
5
-x
3x
x^3+1
-7x^10+3x-1
while the following are not valid:
0x^3          This should just be 0
-0            Negative 0 is not allowed
1+3           Two terms have the same value of b (zero)
x+0           a is equal to 0 for one of the terms, but there is another term
1x            a is equal to 1, and b is not 0
4x^1          b is equal to 1
5--4x         This should be "4x+5"
4+4x          The terms are in the wrong order
4x^2-0x       a is equal to 0 in one of the terms
3x^2+-3       This should be "3x^2-3"
You will be given two valid polynomials. Your task is to add them together and return the resulting polynomial. Your return must follow all of the above rules.

Definition

Class:
PolynomialAdder
Method:
add
Parameters:
String, String
Returns:
String
Method signature:
String add(String poly1, String poly2)
(be sure your method is public)

Notes

  • When adding two polynomials, you should simply find all the terms with the same value of b, and add their a's together (see examples).

Constraints

  • poly1 and poly2 will each contain between 1 and 50 characters, inclusive.
  • poly1 and poly2 will each represent valid polynomials, as defined above.
  • The coefficient of each term (the a part, if it exists) will be between -1000 and 1000, inclusive. Note that this is a constraint on the inputs only, not the outputs (see example 5).
  • The exponent of each term (the b part, if it exists) will be between 0 and 99, inclusive.

Examples

  1. "4x+3"
    "3x^3-x-3"
    Returns: "3x^3+3x"
    The +3 and -3 cancel out, and 4x - x is 3x. Therefore, the result is "3x^3+3x".
  2. "500x^50"
    "0"
    Returns: "500x^50"
  3. "12x+1"
    "-12x-2"
    Returns: "-1"
  4. "5"
    "-5"
    Returns: "0"
  5. "12x^7+34x^5-23x+43"
    "-13x^8-4x^5+3x^2-75"
    Returns: "-13x^8+12x^7+30x^5+3x^2-23x-32"
  6. "1000x^99"
    "1000x^99"
    Returns: "2000x^99"
  7. "x^53-x^52+x^51+x^4-x^3+x^2-x-1"
    "x^54+x^53-x^52-x^50-x^4-x^3+x^2+x-1"
    Returns: "x^54+2x^53-2x^52+x^51-x^50-2x^3+2x^2-2"
  8. "53x^3"
    "-54x^3"
    Returns: "-x^3"
Back to all problems