PAT(Basic Level) Practice : 1019 数字黑洞 (20分)

注意

有几个测试点总是通不过
1.输入是6174的时候,由于while的判断条件程序会直接跳过,必须在while之前进行判断
2.输入N为0<N<1000时,不是四位数,必须在前面进行补零。比如输入3,补成0003

代码

#include <iostream>
#include"stdlib.h"
#include <vector>
#include <cstdio>
#include <algorithm>
#include <sstream>
using namespace std;

vector<string> process(string num)
{
    string n1=num;
    string n2=num;
    string n3="0000";
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3-i;j++)
        {
            if(n1[j]<n1[j+1])
            {
                char temp=n1[j];
                n1[j]=n1[j+1];
                n1[j+1]=temp;
            }
        }
    }
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3-i;j++)
        {
            if(n2[j]>n2[j+1])
            {
                char temp=n2[j];
                n2[j]=n2[j+1];
                n2[j+1]=temp;
            }
        }
    }
    stringstream ss;
    int N1,N2,N3;
    ss<<n1;
    ss>>N1;
    ss.clear();
    ss<<n2;
    ss>>N2;
    N3=N1-N2;
    //cout<<N1<<" "<<N2<<endl;

    n3[0]+=N3/1000;
    N3=N3%1000;

    n3[1]+=N3/100;
    N3=N3%100;

    n3[2]+=N3/10;
    N3=N3%10;

    n3[3]+=N3;


    vector<string> res;
    res.push_back(n1);
    res.push_back(n2);
    res.push_back(n3);
    return res;
}


int main()
{
    string num;
    cin>>num;
    if(num=="6174")
        cout<<"7641"<<" - "<<"1467"<<" = "<<"6174"<<endl;
    if(num.length()<4)
    {
        while(num.length()<4)
        {
            num="0"+num;
        }
    }
    //cout<<num<<endl;
    while(num!="6174")
    {
        vector<string> res=process(num);
        cout<<res[0]<<" - "<<res[1]<<" = "<<res[2]<<endl;
        num=res[2];
        char t=num[0];
        if(num[1]==t&&num[2]==t&&num[3]==t)
        {
            break;
        }
    }
    return 0;
}

上一篇:Python07-04_practice


下一篇:【英语学习】第17周翻译练习之描述他人