Now you are given N integers. Please sort them in ascending order of the sum of their digits. If the sums of digits are the same, sort them in ascending order of the integer values themselves.
Suppose there are 3 positive integers: 1234, 1258, and 5122. The sum of digits for 1234 is 1 + 2 + 3 + 4 = 10; for 1258, it's 16; and for 5122, it's 10. So, the sorted result is 1234, 5122, 1258.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
The first line is a positive integer T (1 ≤ T ≤ 10), indicating the number of test cases. Each test case consists of 2 lines. The first line is a positive integer N (2 ≤ N ≤ 10), indicating there are N positive integers. Then, the second line contains N integers separated by a space, each integer having 3 to 7 digits. | Please output the sorted result for each test case according to the sorting rule. Each line of output must end with a newline character. |
5 3 1234 1258 5122 4 1725 3821 2011 1428 4 1925 2011 3210 9215 4 4145 1245 1485 1478 7 5584 12635 7894 12365 98453 56487 2134567 | 1234 5122 1258 2011 3821 1428 1725 2011 3210 1925 9215 1245 4145 1485 1478 12365 12635 5584 7894 2134567 98453 56487 |
Thought Process
Sure, you can collect the data as strings and then iterate through each character in a for loop to sum up the digits.
That's a good approach! You can declare a vector<pair> to store the sum of digits and the original numbers. Then, use stoi to convert the strings to integers and push them into the vector. Finally, you can sort the vector based on the defined comparison criteria.
Yes, you can iterate through the vector and output only the second field of each pair. You can add a condition to check if the current iteration is the last one and print a new line accordingly.
Sample Code-ITSA 202405 #4: Special Sorting
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
cout.sync_with_stdio(0);
cout.tie(0);
int T;
cin >> T;
for (int i = 0; i<T; i++) {
int N;
cin >> N;
vector<pair<int, int>>v;
for (int j = 0; j<N; j++) {
string str;
cin >> str;
int sum = 0;
for (int k = 0; k<str.length(); k++) sum += str[k] - '0';
pair<int, int>p;
p.first = sum;
p.second = stoi(str);
v.push_back(p);
}
sort(v.begin(), v.end());
for (int j = 0; j<N; j++) {
cout << v[j].second;
if (j != N-1) cout << " ";
}
cout << "\n";
}
}
//ITSA 202405 #4
//Dr. SeanXD