UVA263 LA5372 Number Chains字符串Ad Hoc

Posted 海岛Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA263 LA5372 Number Chains字符串Ad Hoc相关的知识,希望对你有一定的参考价值。

Given a number, we can form a number chain by

  1. arranging its digits in descending order
  2. arranging its digits in ascending order
  3. subtracting the number obtained in (2) from the number obtained (1) to form a new number
  4. and repeat these steps unless the new number has already appeared in the chain

    Note that 0 is a permitted digit. The number of distinct numbers in the chain is the length of the chain. You are to write a program that reads numbers and outputs the number chain and the length of that chain for each number read.
Input
The input consists of a sequence of positive numbers, all less than 109 , each on its own line, terminated
by ‘0’. The input file contains at most 5000 numbers.
Output
The output consists of the number chains generated by the input numbers, followed by their lengths exactly in the format indicated below. After each number chain and chain length, including the last one, there should be a blank line. No chain will contain more than 1000 distinct numbers.
Sample Input
123456789
1234
444
0
Sample Output
Original number was 123456789
987654321 - 123456789 = 864197532
987654321 - 123456789 = 864197532
Chain length 2

Original number was 1234
4321 - 1234 = 3087
8730 - 378 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
Chain length 4

Original number was 444
444 - 444 = 0
0 - 0 = 0
Chain length 2

问题链接UVA263 LA5372 Number Chains
问题简述:(略)
问题分析:字符串处理杂题,不解释。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA263 LA5372 Number Chains */

#include <bits/stdc++.h>

using namespace std;

char num[24], num2[24];

int main()
{
    int n;
    while (cin >> n && n) {
        cout << "Original number was " << n << endl;

        sprintf(num, "%d", n);
        sort(num, num + strlen(num));
        strcpy(num2, num);
        reverse(num2, num2 + strlen(num2));
        int first = atoi(num2);
        int second = atoi(num);
        int sub = first - second;
        cout << first << " - " << second << " = " << sub << endl;

        int cnt = 1;
        map<int, int> m;
        while(m[sub] == 0) {
            m[sub] = 1;
            sprintf(num, "%d", sub);
            sort(num, num + strlen(num));
            strcpy(num2, num);
            reverse(num2, num2 + strlen(num2));
            first = atoi(num2);
            second = atoi(num);
            sub = first - second;
            cout << first << " - " << second << " = " << sub << endl;
            cnt++;
        }
        cout << "Chain length " << cnt << endl << endl;
    }

    return 0;
}

以上是关于UVA263 LA5372 Number Chains字符串Ad Hoc的主要内容,如果未能解决你的问题,请参考以下文章

263. Ugly Number

263. Ugly Number

LeetCode 第 263 题 (Ugly Number)

263. Ugly Number

leetcode 263: Ugly Number

263. Ugly Number