题目
题解1
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 获取位数和
int getWeishuhe(int n){
int sum=0;
while(n!=0){
sum+=n%10;
n/=10;
}
return sum;
}
// 自定义比较函数
bool myCompare(int a, int b) {
if (getWeishuhe(a)!=getWeishuhe(b)){
return getWeishuhe(a)>getWeishuhe(b);
}
return a > b;
}
int main() {
int n;
cin >> n;
std::vector<int> numbers;
for (int i=0;i<n;i++){
int data;
cin >> data;
numbers.push_back(data);
}
// 使用自定义的比较函数进行排序
std::sort(numbers.begin(), numbers.end(), myCompare);
// 输出排序后的结果
for (int number : numbers) {
std::cout << number << " ";
}
return 0;
}
题解2
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 获取位数和
int getWeishuhe(int n){
int sum=0;
while(n!=0){
sum+=n%10;
n/=10;
}
return sum;
}
// 自定义比较函数
bool myCompare(int a, int b) {
if (getWeishuhe(a)!=getWeishuhe(b)){
return getWeishuhe(a)>getWeishuhe(b);
}
return a > b;
}
int main() {
int n;
cin >> n;
int numbers[1100];
for (int i=0;i<n;i++){
cin >> numbers[i];
}
// 冒泡排序
for (int i=0;i<n;i++){
for (int j=0;j<n-i-1;j++){
if (!myCompare(numbers[j],numbers[j+1])){
int t=numbers[j];
numbers[j]=numbers[j+1];
numbers[j+1]=t;
}
}
}
// 输出排序后的结果
for (int i=0;i<n;i++){
cout << numbers[i] << " ";
}
return 0;
}
谢谢
谢谢