ZeroJudge K645: Math Tools

Jasmine is a third-grade elementary school student. She is learning addition operations.

The teacher wrote down a series of equations, and the students had to calculate the sum of the equations. However, this is not enough for Jasmine. She has just started learning how to count, so Jasmine can only calculate the sum when the addends are sorted in non-decreasing order. For example: she cannot calculate 1+3+2+1, but she can calculate 1+1+2+3.

You have the equations written on the blackboard. Rearrange the equations in a way that Jasmine can calculate the total sum.

Sample Inputs/Outputs

Sample Input(s)Sample Output(s)
The input is a non-empty string, s, representing the equations written on the blackboard. The string s does not contain any spaces. It only consists of numbers and the character '+' which represents addition. Additionally, the string s represents the correct sum of the numbers 1, 2, and 3. The length of string s is at most 1000 characters.Print the new equation that Jasmine can calculate.
3+2+11+2+3
22

Thought Process

Use a string to collect the equation and extract the numbers, storing them in an array. If there is only one number in the array, output that number. Otherwise, sort the array and output it with "+" between each number.

Sample Code-ZeroJudge K645: Math Tools

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int toint(string str) {
    if (str.length() == 1) return int(str[0] - '0');
    return stoi(str);
}

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    string str, tmp = "";
    cin >> str;
    vector<int>num;
    for (int i = 0; i<str.length(); i++) {
        if (str[i] == '+' && tmp.length() > 0) {
            num.push_back(toint(tmp));
            tmp = "";
        }
        tmp += str[i];
    }
    if (tmp.length() > 0) num.push_back(toint(tmp));
    sort(num.begin(), num.end());
    cout << num[0];
    if (num.size() > 1) {
        for (int i = 1; i<num.size(); i++) {
            cout << '+' << num[i];
        }
    }
    cout << "\n";
}

//ZeroJudge K645
//Dr. SeanXD

Comments