文章目录
Author: CHEN, Yue
Organization: 浙江大学
Time Limit: 400 ms
Memory Limit: 64 MB
Code Size Limit: 16 KB
A1023 Have Fun with Numbers (20point(s))
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
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
using namespace std;
char num[21];
vector<int> vi;
int htable[10], flag = 1;
int main(){
memset(htable, 0, sizeof(htable)); // 表初始置零
scanf("%s", num);
for (int i = 0; i < strlen(num); i++){
htable[num[i] - '0']++; // 记录每一个数字出现的次数
vi.push_back((num[i] - '0') * 2);
}
for (int i = vi.size()-1; i > 0; i--){ // 这里我们不对vi[0]进位,因为如果vi[0]需要进位,那么结果一定为“No”
if (vi[i] / 10){ // 由于本题只是将每位数据乘二,所以在一个vi[i]中不会出现三位数
vi[i - 1] += vi[i] / 10;
vi[i] = vi[i] % 10;
}
htable[vi[i]]--; // 数字出现过就把对应表的值--
}
if (vi[0] / 10){ // 如果最高位需要进位,即乘二后数字加长一位
printf("No\n");
for (int i = 0; i < vi.size(); i++)
printf("%d", vi[i]);
printf("\n");
return 0;
}
htable[vi[0]]--;
for (int i = 0; i < vi.size(); i++){
if (htable[vi[i]]){ // 有数字多出现了,当然这种情况下表中必有负值
printf("No\n");
flag = 0;
break;
}
}
if (flag) printf("Yes\n");
for (int i = 0; i < vi.size(); i++) printf("%d", vi[i]);
printf("\n");
return 0;
}
Analysis
-已知一个k位的数字。
-求,将这个数字乘以2后,如果新的数字里的每一位和原数字的每一位中各种数字(0-9)出现的次数完全相同,则输出Yes,否则输出No。