• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
村雨sup
自己选的路,跪着也要走完 XD
博客园    首页    新随笔    联系   管理    订阅  订阅
PAT 1069 The Black Hole of Numbers
1069 The Black Hole of Numbers (20 分)
 

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 (.

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

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;


bool comp(char a,char b){
    return a>b;
}

int to_int(string s){
    int sum = 0;
    for(int i=0;i < s.size();i++){
        int num = s[i] - '0';
        sum = sum*10 + num;
    }
    return sum;
}


string minuss(string s1,string s2){
    string res;
    int a = to_int(s1);
    int b = to_int(s2);
    int c = a - b;
    res = to_string(c);
    int len = res.size();
    for(int i=0;i < (4-len);i++){ //加前导0;
        res = "0"+res;
    }
    return res;
}

int main(){

    string s;cin >> s;
    int len = s.size();
    for(int i=0;i < (4-len);i++){ //加前导0;
        s = "0"+s;
    }
    string s1 = s,s2 = s;
    sort(s1.begin(),s1.end(),comp);
    sort(s2.begin(),s2.end());
    string ans = minuss(s1,s2);
//    cout << ans;
    if(ans == "0000"){
        printf("%s - %s = %s\n",s1.c_str(),s2.c_str(),ans.c_str());
        return 0;
    }
    else{
        printf("%s - %s = %s\n",s1.c_str(),s2.c_str(),ans.c_str());
    }

    while(ans!="6174"){
        s1 = ans; s2 = ans;
        sort(s1.begin(),s1.end(),comp);
        sort(s2.begin(),s2.end());
        ans = minuss(s1,s2);
        printf("%s - %s = %s\n",s1.c_str(),s2.c_str(),ans.c_str());
    }

    return 0;
}

贼弱智,说是四位数,你给个0~10000范围,补前导0还算数字,服了

posted on 2019-04-26 00:36  村雨sup  阅读(175)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3