1023 Have Fun with Numbers (20 分)
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
题型分类:字符串处理
题目大意:对输入的一串数字,加倍以后,查看新的一串数字是否是原来数字的排序。
解题思路:中心思想是模拟大数乘法运算。对于判断是否是原来数字的另一种排列,使用hashTable数组记录出现的数字的次数,原数字串出现一个数字,就让hashTable对应那个数字的值加一;新数字串出现一个数字,就让hashTable对应那个数字的值减一,最后判断hashTable里面的值是否为全0。
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
const int maxn = 25;
int hashTable[10]; //表示数字0-9出现的次数
int num[maxn], doubleNum[maxn];
int main(int argc, char** argv) {
string str;
cin >> str;
int carry = 0, len = 0;
for(int i = str.length() - 1; i >= 0; i--, len++) {
num[len] = str[i] - '0';
doubleNum[len] = (carry + num[len] * 2) % 10;
carry = (carry + num[len] * 2) / 10;
hashTable[num[len]]++;
hashTable[doubleNum[len]]--;
}
bool flag = false;
for(int i = 0; i <= 9; i++){
if(hashTable[i] != 0) flag = true;;
}
if(carry > 0){
doubleNum[len++] = 1;
flag = true; //位数都不相同了,就不可能是原始数字的排列了
}
if(flag) printf("No\n");
else printf("Yes\n");
for(int i = len - 1; i >= 0; i--){
printf("%d", doubleNum[i]);
}
return 0;
}