PAT 甲级 1023 Have Fun with Numbers

https://pintia.cn/problem-sets/994805342720868352/problems/994805478658260992

Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!

Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.

Input Specification:

Each input file contains one test case. Each case contains one positive integer with no more than 20 digits.

Output Specification:

For each test case, first print in a line "Yes" if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or "No" if not. Then in the next line, print the doubled number.

Sample Input:

1234567899

Sample Output:

Yes
2469135798

题解: long long 会爆掉 所以字符串模拟加法
代码:
#include <cstdio>
#include <string>
#include <stack>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

char s[2222], num[2222], sum[2222], c, summ[2222];

int main() {
	scanf("%s", s);
	int dot = 0;
	bool flag = true;
    int len = strlen(s);
    int k = 0, ans = 0;
    for(int i = len - 1; i >= 0; i--) {
        sum[ans++] = '0' + (s[i] - '0' + s[i] - '0' + k) % 10;
        k = (s[i] - '0' + s[i] - '0' + k) / 10;
    }
    if(k) {
        sum[ans++] = '1';
        flag = 0;
    }
    for(int i = 0; i <= ans / 2 - 1; i++)
        swap(sum[i], sum[ans - i - 1]);
    strcpy(summ, sum);
    sort(s, s + len);
    sort(summ, summ + ans);
    if(strcmp(s, summ) != 0) flag = 0;
	if(flag) printf("Yes\n");
	else printf("No\n");
    printf("%s\n", sum);
	return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/zlrrrr/p/9427841.html