【PTA-A】1023 Have Fun with Numbers(大整数)
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 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
思路:
1.用字符串存储数字,另存数字到num数组。同时记录每个数字的次数存入a数组。
2.对num操作,从数字最后一位向前遍历,对每一位2倍后取余存入temp数组,如果≥10,前一位进一
3.遍历过程中每得出一位数字,a数组中相应次数-1
4.看a数组是否全为0,全为0说明前后个数相同
注意点:
1.存储数字时从第1位开始,因为第0位可能会进位
2.如果长度不相同【即num[0]!=0】则为No,如果最后a数组中不为0则为No。
3.数字的第0位如果不是0要输出
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main() {
string s;
int a[15] = { 0 }, num[25] = { 0 }, temp[25] = { 0 };
cin >> s;
for (int i = 0; i < s.length(); i++) {
a[s[i] - '0']++; //记录每个数字个数
num[i + 1] = s[i] - '0'; //存储数字,从第1位开始
}
for (int i = s.length(); i > 0; i--) {
temp[i] += num[i] * 2; // //2倍后的数字
if (temp[i] >= 10) {
temp[i] %= 10;
temp[i - 1]++; //进位
}
a[temp[i]]--; //对应数字个数减1
}
int flag = 1;
for (int i = 0; i < 10; i++) {
if (a[i] != 0) {
cout << "No" << endl;
flag = 0;
break;
}
}
if (flag)cout << "Yes"<<endl;
for (int i = 0; i < s.length() + 1; i++) {
if (i == 0 && temp[i] != 0)cout << temp[i]; //第0位判断是否为0
if (i != 0)cout << temp[i];
}
return 0;
}

浙公网安备 33010602011771号