如何输入整数并将其从最高到最低排序
How do you input an integer and have it sorted from highest to lowest
如何输入整数并将其从高到低排序(例如。我输入123456,它输出654321,输入可以自定义)。我有一个大数字的问题。
我有一个大数字的问题。
整数类型在范围上受到限制。为避免此类问题,请将输入视为字符串,然后仅对字符串中的字符进行排序。
对于错误处理,您可能需要检查输入是否仅由数字组成。
阅读std::string
、std::sort
、std::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;
}
相关文章:
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 读取一组用户输入,按升序排序,然后打印结果
- 如何按升序对输入文件中的数字进行排序,并找到它们的范围和中值
- 如何从输入的文本文件中按姓氏字母顺序对图表进行排序?
- 切换输入用于排序算法
- 当输入向量称为储备金时,STD ::排序无法正常工作
- 根据输入文本对单词进行排序,具体取决于重复多少次
- 气泡排序问题不会更改输入阵列
- 无法让我的代码正确排序用户输入的数字数组(使用递归)
- 快速排序算法,一些特定输入序列的错误答案和分段错误
- 如何输入整数并将其从最高到最低排序
- 根据这些字符串输入在句子中的位置对这些字符串输入进行排序的更快方法是什么
- 合并排序 - 返回新数组,而不是将合并的数组复制到输入数组
- 如何输入字符串对容器进行排序
- 为什么大多数STL算法都需要将排序数据作为输入
- 当输入大小足够大时,合并排序崩溃
- 面试难题:用有限的记忆对输入的一百万个数字进行排序
- std::map 的排序顺序取决于输入值
- 有没有选择排序优于冒泡排序的输入