递 增(串)
时间: 1ms 内存:64M
描述:
输入一数字字符串,以值递增的形式输出。
以#表示输入结束,输入可以包含多个空格。
要求判断输入的合法性。
输入:
123 s 34#
123 23 78 76#
23 01 01 001 54 32 #
输出:
输入错误,请重新输入,输入样例:123 34 45#
23 76 78 123
1 1 1 23 32 54
示例输入:
11 1 4 2#
示例输出:
1 2 4 11
提示:
参考答案(内存最优[1120]):
#include<stdio.h>
#include<string.h>
#define MaxSize 101
int main()
{
char str[MaxSize];
int count = 0,i,j;
while(scanf("%c",&str[count])&&str[count]!='#')
{
count++;
}
for(i = 0; i<count; i++)
{
if(!((str[i]>='0'&&str[i]<='9')||str[i]==' '||str[i]=='#'||str[i]=='-'))
{
printf("输入错误,请重新输入,输入样例:123 34 45#");
break;
}
}
int now=0,flag = 0,temp;
int a[101],count1 = 0,count2 = 0;
for(i = 0;i<count;i++)
{
if(str[i]>='0'&&str[i]<='9')
{
now*=10;
now+=str[i]-'0';
flag = 0;
count2++;
}
if(str[i]==' '&&flag == 0)
{
if(str[i-count2-1]=='-')
{
now = (-1)*now;
}
a[count1] = now;
count1++;
now = 0;
flag = 1;
count2 = 0;
}
}
if(now!=0)
{
a[count1] = now;
}
if(now==0)
{
count1--;
}
for(i = 0;i<=count1-1;i++)
{
for(j = i+1;j<=count1;j++)
{
if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for(i = 0;i<=count1;i++)
printf("%d ",a[i]);
}
参考答案(时间最优[0]):
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int fcm(const void* a,const void* b)
{
return (*(int*)a-*(int*)b);
}
int main()
{
char a[100];
char n;
int i;
int fcm(const void *,const void *);
int b[100]={0};
int byt=0;
int hefa=1;
int k=0;
int j=0;
while((n=getchar())!='#')
{
if((n>='0'&&n<='9')||n==' '||n=='\n'||n=='-')
{
if(n!='\n')
{
if(n!=' '||(k!=0&&a[k-1]!=' '))
a[k++]=n;
}
else printf("\n");
}
else
{
hefa=0;
}
}
if(a[k-1]==' ') k--;
a[k]='\0';
if(!hefa)
{
printf("输入错误,请重新输入,输入样例:123 34 45# "); //注意这一行的结果
printf("\n");
}
else
{
k=0;
for(i=strlen(a)-1;i>=0;i--)
{
if(a[i]!=' '&&a[i]!='-')
{
b[k]+=((a[i]-'0')*pow(10,byt));
byt++;
}
else
{
if(a[i]=='-')
b[k]=-b[k];
else{
byt=0;
k++;
}
}
}
k++;
qsort(b,k,sizeof(b[0]),fcm);
printf("%d",b[0]);
for(i=1;i<k;i++)
{
printf(" %d",b[i]);
}
printf("\n");
}
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。