nyoj57 6147问题

最优代码(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++,但是最优代码中的将数组拆开的办法可以学习一下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值