C++20 sections · 1024 units
Open in Course

Helpful Maths - Implementation

Complete solution


plaintext
function helpful_maths(s)
digits := empty vector
for each character c in s
if c is a digit then
 add c to digits
 sort(digits.begin(), digits.end())
 print digits[0]
 for i from 1 to size of digits - 1
 print "+" followed by digits[i]
 print newline

The loop collects digits by checking if each character is between '0' and '9'. After sorting, you print the first digit without a plus sign, then loop through the rest adding plus signs before each digit. The time complexity is O(nlogn)O(n \log n) where nn is the number of digits.