pat_b_1019 数字黑洞

来源:互联网 发布:庄周出装 知乎 编辑:程序博客网 时间:2024/06/05 17:24

 

        http://pat.zju.edu.cn/contests/pat-b-practise/1019


        分析:  atoi , itoa 函数不能使用,否则会CE;

                     输入的并不一定是4位数,而是 (0,10000);

 

         代码:

                    

<span style="font-size:18px;">//Êý×ÖºÚ¶´#include <iostream>#include <stdio.h>#include <string>#include <algorithm>#include <string.h>using namespace std;int cmp(char a, char b){    return   a>b;}int getNum(char e[]){    int tmp=0;    int len=strlen(e);    for(int i=0;i<len;i++){        tmp =tmp*10+(e[i]-'0');    }    return tmp;}int main(){    //freopen("in.txt","r",stdin);    int a,b,c;    char n[5],m[5],t[5];    scanf("%s",t);    strcpy(n,"0000"); n[4]='\0';    int len=strlen(t);    int j=3;    for(int i=len-1; i>=0; i--){        n[j--]=t[i];    }    while(1){          strcpy(m,n);          sort(n,n+4,cmp);  a=getNum(n);          sort(m,m+4);      b=getNum(m);          c=a-b;          printf("%s - %s = %04d\n",n,m,c);          if(c==6174 || c==0) break;          strcpy(n,"0000"); n[4]='\0';          int j=3;          while(c){                n[j]=c%10+'0';                j--;                c /=10;          }    }    return 0;}</span>

        

0 0