public function __toString() : string
{
$variable = $this->variable;
// Start with an empty polynomial
$polynomial = '';
// Iterate over each coefficient to generate the string for each term and add to the polynomial
foreach ($this->coefficients as $i => $coefficient) {
if ($coefficient == 0) {
continue;
}
// Power of the current term
$power = $this->degree - $i;
// Build the exponent of our string as a unicode character
$exponent = '';
for ($j = 0; $j < strlen($power); $j++) {
$digit = intval(strval($power)[$j]);
// The j-th digit of $power
$exponent .= self::SYMBOLS[$digit];
// The corresponding unicode character
}
// Get the sign for the term
$sign = $coefficient > 0 ? '+' : '-';
// Drop the sign from the coefficient, as it is handled by $sign
$coefficient = abs($coefficient);
// Drop coefficients that equal 1 (and -1) if they are not the 0th-degree term
if ($coefficient == 1 and $this->degree - $i != 0) {
$coefficient = '';
}
// Generate the $term string. No $variable term if power = 0.
if ($power == 0) {
$term = "{$sign} {$coefficient}";
} else {
$term = "{$sign} {$coefficient}{$variable}{$exponent} ";
}
// Add the current term to the polynomial
$polynomial .= $term;
}
// Cleanup front and back; drop redundant ¹ and ⁰ terms from monomials
$polynomial = trim(str_replace([$variable . '¹ ', $variable . '⁰ '], $variable . ' ', $polynomial), '+ ');
$polynomial = preg_replace('/^\\-\\s/', '-', $polynomial);
$polynomial = $polynomial !== '' ? $polynomial : '0';
return $polynomial;
}