题目:
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!
(译文:数字123456789是一个9位数字,恰好包含从1到9的数字,没有重复。翻倍得到246913578,它恰好是另一个9位数字由1到9组成,只是排列不同。如果我们再翻倍,看看结果如何!)
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.
(译文:现在你应该检查是否有更多的数字具有这个性质。也就是说,将一个给定的数字翻倍,有k个数字,你要判断结果数字是否只包含原始数字的一个排列。)
输入格式:
Each input contains one test case. Each case contains one positive integer with no more than 20 digits.
(译文:每个输入包含一个测试用例。每一种情况包含一个不超过20位的正整数。)
输出格式:
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.
(译文:对于每个测试用例,如果输入的数字加倍,得到的数字只包含原始数字的排列,则首先在一行中打印“Yes”,如果不是,则打印“No”。然后在下一行中,打印加倍的数字。)
要点:(模拟手算乘法)
思路:
1.由于原始数字可能会很大,用long long int也未必能满足要求,故优先考虑通过字符数组a1[]接收数据,再将其转入相应的int型数组a[]中(例:字符‘1’转化为数字1 — ‘1’-‘0’或者‘1’-48)
2.此时模拟手算乘法过程,见上图,将结果保存在ret[]数组中;
3.将数组a[]中的数字依次作为数组cnt[]的下标,并累加;将数组ret[]中的数字作为下标,并累减;
cnt[]初始化为0;若最终遍历cnt[]值均为0,则a[]与ret[]相应数字出现的个数相同
4.打印结果
注:(自己挖的坑自己填o(╥﹏╥)o)
在思路-3中,有个隐藏坑(初始化为0),假设原来数据在数组中存放表示为0000xxxxxx,乘积在数组中的存放表示为000x0xxxxx(假设此情况满足乘法前后1-9出现次数相同),可看出此时0出现次数也相同,按照上述方法会判定为“Yes”,但很明显原数列中不存在0,而结果数列中出现了0,这样的结果是不对的,,,
解决办法:分别记录原数中0的个数和结果中0的个数,具体操作见代码部分
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main(){
//1.将输入的正整数存放在数组中
char a1[20] = {'0'};
scanf("%s", a1); //字符数组(此时是倒序存储,即a1[0]存放整数最高位)
int len1 = strlen(a1);
int a[21]={0};
int num0_a = 0;
for (int i = 0; a1[i] != '\0'; i++) { //整型数组(将原数顺序存储,即a[0]存放整数最低位,便于模拟手算乘法)
a[i] = a1[len1 - 1 - i]-48;
if (a[i] == 0) {
num0_a++;; //填坑处1:记录原数中0出现的次数
}
}
//2.模拟手算乘法,将乘以2的结果保存在新数组中
int ret[21] = {0};
int t = 0,k=2;
int len2 = 0;
int num0_ret = 0;
for (int i = 0; i < 21; i++) {
ret[i] = a[i] * k % 10+t;
t = a[i] * k / 10;
if (ret[i] != 0) {
len2 = i+1; //填坑处2:记录乘积的位数,便于计录乘积中0的个数
}
}
//3.统计原数中1-9出现的次数,与乘积中出现的次数对比
int cnt[10] = { 0 };
int flag;
for (int i = 0; i < 21; i++) {
int temp1= a[i];
cnt[temp1]++;
int temp2 = ret[i];
cnt[temp2]--;
if (i < len2 && ret[i] == 0) {
num0_ret++; //填坑处3:记录乘积中0的个数
}
}
for (int j = 1; j < 10; j++) { //遍历数据看是否为0
flag = 1;
if(cnt[j]!=0) {
flag = 0;
break;
}
}
if (num0_a!=num0_ret) { //填坑处4:判断原数和乘积中0的个数是否相等
flag = 0;
}
if (1 == flag) {
printf("Yes\n");
}
else {
printf("No\n");
}
//4.打印乘积
int f = 0;
for (int k = 20; k >= 0; k--) {
if (ret[k] != 0) {
f = 1;
printf("%d", ret[k]);
}
else if (ret[k] == 0 && f == 1) {
printf("%d", ret[k]);
}
}
return 0;
}
★要是觉得有帮助,就点个赞吧☛