如何输入整数并将其从最高到最低排序

How do you input an integer and have it sorted from highest to lowest

本文关键字:排序 何输入 输入 整数      更新时间:2023-10-16

如何输入整数并将其从高到低排序(例如。我输入123456,它输出654321,输入可以自定义)。我有一个大数字的问题。

我有一个大数字的问题。

整数类型在范围上受到限制。为避免此类问题,请将输入视为字符串,然后仅对字符串中的字符进行排序。

对于错误处理,您可能需要检查输入是否仅由数字组成。

阅读std::stringstd::sortstd::greater等。

// Input
std::string s = "123456";
// Sort descending
std::sort(s.begin(), s.end(), std::greater<char>());

我认为下面的代码会适合你。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool Isnum(char ch)
{
    if(ch >= 48 && ch <= 57)
        return true;
    else
        return false;
}
bool compare(char a,char b)
{
    return a>b;
}
int main()
{
    string num;
    cin >> num;
    cout << num << endl;
    int i;
    for(i=0;i<num.length();i++)
    {
        if(!Isnum(num[i]))
        {
            cout << "Enter a valid number";
            return 0;
        }
    }
    sort(num.begin(),num.end(),compare);
    cout << num;

   return 0;
}