zoukankan      html  css  js  c++  java
  • PAT Basic 1019 数字黑洞 (20 分)

    给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174,这个神奇的数字也叫 Kaprekar 常数。

    例如,我们从6767开始,将得到

    7766 - 6677 = 1089
    9810 - 0189 = 9621
    9621 - 1269 = 8352
    8532 - 2358 = 6174
    7641 - 1467 = 6174
    ... ...
    

    现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。

    输入格式:

    输入给出一个 ( 区间内的正整数 N。

    输出格式:

    如果 N 的 4 位数字全相等,则在一行内输出 N - N = 0000;否则将计算的每一步在一行内输出,直到 6174 作为差出现,输出格式见样例。注意每个数字按 4 位数格式输出。

    输入样例 1:

    6767
    

    输出样例 1:

    7766 - 6677 = 1089
    9810 - 0189 = 9621
    9621 - 1269 = 8352
    8532 - 2358 = 6174
    

    输入样例 2:

    2222
    

    输出样例 2:

    2222 - 2222 = 0000
    #include <iostream>
    using namespace std;
    int sortInt(int a){
        int hash[10]={0};
        while(a!=0){
            hash[a%10]++;
            a/=10;
        }
        for(int i=9;i>=0;i--){
            while(hash[i]!=0){
                a=a*10+i;
                hash[i]--;
            }
        }
        int plus;
        if(a>=1000) plus=1;
        else if(a<1000&&a>=100) plus=10;
        else if(a<100&&a>=10) plus=100;
        else plus=1000;
        return a*plus;
    }
    int reverse(int a){
        int plus;
        if(a>=1000) plus=1;
        else if(a<1000&&a>=100) plus=10;
        else if(a<100&&a>=10) plus=100;
        else plus=1000;
        int ans=0;
        while(a!=0){
            ans=ans*10+a%10;
            a/=10;
        }
        return ans*plus;
    }
    int main()
    {
        int a,b;
        cin>>a;
        if(a==6174) printf("7641 - 1467 = 6174
    ");
        while(a!=6174&&a!=0){
            a=sortInt(a);
            b=reverse(a);
            printf("%04d - %04d = %04d
    ",a,b,(a-b));
            a=a-b;
        }
        system("pause");
        return 0;
    }
  • 相关阅读:
    基于Python的人脸动漫转换
    let 与 var的区别
    【LeetCode】汇总
    【HDU】4632 Palindrome subsequence(回文子串的个数)
    【算法】均匀的生成圆内的随机点
    【LeetCode】725. Split Linked List in Parts
    【LeetCode】445. Add Two Numbers II
    【LeetCode】437. Path Sum III
    【LeetCode】222. Count Complete Tree Nodes
    【LeetCode】124. Binary Tree Maximum Path Sum
  • 原文地址:https://www.cnblogs.com/littlepage/p/11406820.html
Copyright © 2011-2022 走看看