PAT 1069. The Black Hole of Numbers (20) 【超时14/20】
2014-03-16 10:30
399 查看
1069. The Black Hole of Numbers (20)
时间限制100 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner
we will soon end up at the number 6174 -- the "black hole" of 4-digit numbers. This number is named Kaprekar Constant.
For example, start from 6767, we'll get:
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range (0, 10000).
Output Specification:
If all the 4 digits of N are the same, print in one line the equation "N - N = 0000". Else print each step of calculation in a line until 6174 comes out as the difference. All the numbers must be printed as 4-digit numbers.
Sample Input 1:
6767
Sample Output 1:
7766 - 6677 = 1089 9810 - 0189 = 9621 9621 - 1269 = 8352 8532 - 2358 = 6174
Sample Input 2:
2222
Sample Output 2:
2222 - 2222 = 0000
提交代码
不知道为什么会超时。。14/20
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; char ans[10]; bool cmp(char ch1,char ch2) { return ch1>ch2; } char* minusNum(char t1[],char t2[]) { int i,carry=0; for(i=3;i>=0;i--){ if(t1[i]-'0'-carry<t2[i]-'0'){ ans[i]=t1[i]-carry-t2[i]+10+'0'; //注意计算完后 还要转化成字符!!! carry=1; } else{ ans[i]=t1[i]-carry-t2[i]+'0'; carry=0; } } ans[4]='\0'; //构成字符串~ return ans; } int main() { //freopen("G:\\in.txt","r",stdin); int i; char r[10],a[10],b[10]; while(scanf("%s",r)!=EOF){ memset(a,0,sizeof(a));memset(b,0,sizeof(b)); for(i=1;i<4;i++){ if(r[i]==r[0]) continue; else break; } if(i==4){ printf("%s - %s = 0000\n",r,r); continue; } do{ sort(r,r+4); //默认升序 strcpy(a,r); sort(r,r+4,cmp); //降序排列 strcpy(b,r); strcpy(r,minusNum(b,a)); printf("%s - %s = %s\n",b,a,r); }while(strcmp(r,"6174")!=0); } return 0; }
相关文章推荐
- Linux 下使用命令行开发 Android 应用程序
- CListBox::GetSelItems的用法
- OpenGL学习记录4
- SQL查询基本结构
- <<J2SE>>Java代码自写9Path算法
- PL/SQL Developer+Oracle 连接远端数据库
- Multiply Strings[LeetCode]
- Java设计模式之一(简单工厂模式)
- 玩转html5<canvas>画图
- Nginx学习笔记(十六):worker进程的循环工作
- C++第3周(春)项目3 时间类
- 如何做一名好的web安全工程师?
- Nexus搭建私服
- _存储一些有用的链接
- 侧边栏SlidingMenu的应用
- 关于VirtualBOX安装错误:VERR_MODULE_NOT_FOUND的解决方法。
- redhat Linux 安装 VMware tools方法
- NYOJ-多边形重心问题(计算几何)
- Sharepoint 2013企业内容管理学习笔记终章
- 九度题目1186:打印日期