Addition Affliction
InterviewTime limit1sMemory limit256 MB
Reorder each sum so numbers that pair to a multiple of 10 come first in adjacent pairs, using the most pairs and the smallest lexicographic order.
Problem
Albert is a computer science student who loves math. His grasp of the basics is weak, and addition has given him trouble since he was small.
Addition keeps coming up in daily life, so Albert wants to get comfortable with it at last. The way he sees it, an addition is easiest when the numbers add up to a multiple of 10.
Doing the work for him would not help him practice. Reorder the terms of each practice expression instead, so that the expression is easier for him to work through.
Input
The input has several lines. Each line is a sum of nonnegative integers written as
with , and every satisfies . Every number is written without leading zeros.
A line has no whitespace and contains only digits and plus signs. There are at most 100 expression lines. A line holding only 0 ends the input, and that line is not processed.
Output
For each expression print one line holding the terms in a new order. The order must follow these rules.
Two numbers whose sum is a multiple of 10 form a pair. A number belongs to at most one pair, and the number of pairs must be as large as possible, so no two unpaired numbers may add up to a multiple of 10. Every paired number comes before every unpaired number, and the two numbers of a pair are next to each other.
Several orders can satisfy the rules. Print the one that comes first in lexicographic order. Compare two orders term by term by numeric value, and the order with the smaller value at the first position where they differ comes first.
Write the answer in the same form as the input: a plus sign between consecutive numbers and no whitespace.