数字游戏(string的sort的应用)

题目描述

牛牛举办了一场数字游戏,有n个玩家参加这个游戏,游戏开始每个玩家选定一个数,然后将这个数写在纸上(十进制数,无前缀零),然后接下来对于每一个数字将其数位按照非递减顺序排列,得到新的数,新数的前缀零将被忽略。得到最大数字的玩家赢得这个游戏。

输入描述:

输入包括两行,第一行包括一个整数n(1 ≤ n ≤ 50),即玩家的人数
第二行n个整数x[i](0 ≤ x[i] ≤ 100000),即每个玩家写下的整数。

输出描述:

输出一个整数,表示赢得游戏的那个玩家获得的最大数字是多少。
示例1

输入

复制
3
9638 8210 331

输出

复制
3689

解题思路1:利用string的排序函数(非降序就是升序)以及atoi(x.c_str())转化函数的应用就可以进行解题
#include<stdlib.h>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
    int n,i,Max=-1;
    for(cin>>n,i=0;i<n;i++){
        string x;
        cin>>x,sort(x.begin(),x.end());
        Max=max(Max,atoi(x.c_str()));
    }
   cout<<Max;

}

解题思路2:不利用string的特性自己进行按位取出来再赋值给另一个数组,之后调用整数的sort()函数进行排序//不推荐

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
    int n;
    cin>>n;
    int* x=new int[n];
    int* rev=new int[n];
    for(int i=0;i<n;i++){
        cin>>x[i];
        int a[6],count=0,temp1=x[i],temp2=0;
        while(temp1>0){
            a[count++]=temp1%10;
            temp1/=10;
        }
        sort(a,a+count);
        for(int j=0;j<count;j++)
            temp2=temp2*10+a[j];
        rev[i]=temp2;
    }
    sort(rev,rev+n);
    cout<<rev[n-1]<<endl;
    delete(x);delete(rev);
}

猜你喜欢

转载自www.cnblogs.com/cstdio1/p/10993198.html