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++,但是最优代码中的将数组拆开的办法可以学习一下。
#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++,但是最优代码中的将数组拆开的办法可以学习一下。
相关文章推荐
- 学习windows驱动(创建IO请求)
- weinre 搭建(简单版)
- 需求工程-软件建模与分析读书笔记3
- C语言文法
- python类方法
- shellinabox终端模拟器安装
- win10新功能曝光之改善4K屏显示效果
- 用NodeJS 做反向代理服务器
- 整理一个用matrix对imageview移动和绽放图片的方法
- 重视问题1
- python语法
- 1014 C语言文法定义与C程序的推导过程
- SQL 统计整个服务器上各个数据库占用的空间
- tar指定解压路径
- Android android:clickable 问题
- Mysqldump参数大全
- 个人笔记 js 07 js向select里添加option
- iOS设置label行间距的方法
- Linux cgroup机制分析之cpuset subsystem
- Android定时器