• 1019 数字黑洞


    注意测试点可能为6174,已经循环结束条件应为(n != 6174 && n != 0)

    用stl和普通方法各写了一次。

    普通方法:

    #include <iostream>
    #include<string>
    #include<stdio.h>
    #include<algorithm>
    using namespace std;
    bool cmp(char a, char b) {
        return a > b;
    }
    int main() {
        char ch[5];
        int n;
        cin.getline(ch, 5);
        sscanf(ch, "%d", &n);
      
        if (n == 6174)
        {
            cout << "7641 - 1467 = 6174";
            return 0;
        }
    
        while (n != 6174&&n!=0) {
            int i;
            for (i = 0; i < 4; i++)
                if (ch[i]== '\0')
                    break;
            fill(ch + i, ch + 4, '0');//说明不够4位数,把不够的位数用0补足。
            ch[4] = '\0';//一定要加上‘\0’
            
            int a, b;
    
            sort(ch, ch + 4, cmp);
            cout << ch;//打印递减的ch
            sscanf(ch, "%d", &a);//字符串转整型。
            sort(ch, ch + 4);
            cout << " - " << ch << " = ";//打印递增的ch
            sscanf(ch, "%d", &b);
            n = a - b;
            printf("%04d\n", n);
            sprintf(ch, "%d", n);
        }
    
    }

    stl方法:

    #include <iostream>
    #include<string>
    #include<stdio.h>
    #include<algorithm>
    using namespace std;
    bool cmp(char a, char b) {
        return a > b;
    }
    int main() {
        string ch;
       
        getline(cin, ch);
        
      
        if (ch == "6174")
        {
            cout << "7641 - 1467 = 6174";
            return 0;
        }
    
        while (ch != "6174"&&ch!="0") {
            int a,b,n;
            if(ch.size()<4)
                ch.insert(0,4-ch.size(),'0');
            
    
            sort(ch.begin(), ch.end(), cmp);
            cout << ch;//打印递减的ch
            a=stoi(ch);//字符串转十进制整型。
            sort(ch.begin(), ch.end());
            cout << " - " << ch << " = ";//打印递增的ch
            b=stoi(ch);//字符串转十进制整型
            n = a - b;
    
            printf("%04d\n", n);
            ch=to_string(n);//整型转字符串。
        }
    
    }
  • 相关阅读:
    webpack(二)
    webpack(一)
    初探Vue SSR(1)
    Node版本管理控制器n
    Gitlab用户在组中有五种权限:Guest、Reporter、Developer、Master、Owner
    微信小程序分享参数传递
    关于vue-cli3.*搭建项目遇到问题整理
    请求头出现provisional headers are shown 和 vue-cli 3.x配置跨域代理
    HDU6409 没有兄弟的舞会
    HDU6446 Tree and Permutation
  • 原文地址:https://www.cnblogs.com/kalicener/p/12444740.html
Copyright © 2020-2023  润新知