- 题目:
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
-
题目大意
给定一个位数不超过20位的正整数a,求2a与a中所含的数字是否相同 -
分析
输入string a,将其存储在整数数组A中,然后将数组中每个数字扩大二倍,注意进位
并新建两个hash散列,初始值位1,将A中每个数字设置在hash中设置位0,最后比较两个hash散列中存储的数字是否完全相同。不同,则输出No,否则输出Yes,最后输出2a -
代码实现:
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int map1[10] = {1}, map2[10] = {1};
int main()
{
string num;
cin >> num;
vector<int> A(21);
for(int i = 0; i < 10; i++){ //初始化散列
map1[i] = 1;
map2[i] = 1;
}
int len = num.length();
for(int i = 0; i < len; i++){
A[i] = num[i] - '0';
map1[A[i]] = 0;
}
reverse(A.begin(), A.begin() + len); //逆转向量
//数组乘法
int tag = 0; //进位
for(int i = 0; i < len; i++){
A[i] = 2*A[i] + tag;
if(A[i] >= 10)
tag = 1;
else
tag = 0;
A[i] = A[i] % 10;
map2[A[i]] = 0;
}
if(tag == 1){ //处理最后一位
A[len] = 1;
len++;
map2[1] = 0;
}
bool tag2 = true;
for(int i = 0; i < 10; i++){ //比较两个散列是否完全相同
if(map1[i] != map2[i]){
tag2 = false;
break;
}
}
if(tag2)
cout << "Yes" << endl;
else
cout << "No" <<endl;
for(int i = len-1; i >= 0; i--){
cout <<A[i];
}
return 0;
}