您的位置:首页 > 其它

nyoj57 6147问题

2015-10-29 16:19 330 查看
最优代码(c++):

#include<iostream>

#include<algorithm>

#include<stdio.h>

using namespace std;

int main()

{

//freopen("1.txt","r",stdin);

int k;

cin>>k;

while(k--)

{

int n,a[4],n1,n2;

scanf("%d",&n);

int s=1;

while(n!=6174)

{

a[0]=n%10;

a[3]=n/1000;

a[1]=n/10%10;

a[2]=n/100%10;

sort(a,a+4);

n1=1000*a[3]+100*a[2]+10*a[1]+a[0];

n2=1000*a[0]+100*a[1]+10*a[2]+a[3];

n=n1-n2;

s++;

}

printf("%d\n",s);

}

}

本人写的代码:

#include<stdio.h>

int main()

{

int n,i,j;

char str[6];

scanf("%d",&n);

while(n--)

{

scanf("%s",&str);

for(i = 0;i < 4;i++ )

{

str[i] = str[i] - '0';

}

int num = str[0]*1000 + str[1]*100 + str[2]*10 +str[3];

int count = 1,max,min;

while(num !=6174)

{

//从小到大排序

for( i = 0; i < 4;i++ )

{

for(j = 0; j < 3-i ;j++)

{

if(str[j] > str[j + 1])

{

int temp = str[j];

str[j] = str[j + 1];

str[j + 1] = temp;

}

}

}

max = str[3]*1000 + str[2]*100 + str[1]*10 +str[0];

min = str[0]*1000 + str[1]*100 + str[2]*10 +str[3];

num = max - min;

int num1 = num;

for(int k = 3;k >= 0;k--)

{

str[k] = num1%10;

num1 = num1/10;

}

count++;

}

printf("%d\n",count);

}

return 0;

}

小结:我竟然不知道数组也可以存整型,还在字符和数字间纠结了好久。由于C语言中没有内置的排序函数,我用了buble排序,我不太会c++,但是最优代码中的将数组拆开的办法可以学习一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: