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.题目大意:将输入的数乘2,然后看结果是否是原来输入的数的重新排列。
2.将原来数和结果数数字的个数用map存起来,key是数字,value是该数字出现的个数。
3.结果数可能超出unsigned long long int的取值范围,所以与大数加法类似,原来的数和结果数都用字符串存,由字符串的大数乘法得到结果数
4.判断结果数是否为原来数的重新排列的条件为:1)存了各自数字出现个数的两个map容器相等 2)两个字符串数的长度相等(验证总数是否相等)
AC代码
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
string s,ss;
map <char,int> m1,m2;
int temp,add,k=0;
bool flag=false;
cin>>s;
ss.resize(s.length());
while(s.length()-k>0)
{
m1[s[s.length()-k-1]]++;
if(flag)
add=temp;
else
add=0;
temp=0;
flag=false;
add+=(s[s.length()-k-1]-'0')*2;
while(add>=10)
{
add-=10;
temp++;
flag=true;
}
ss[ss.length()-k-1]=add+'0';
k++;
}
if(flag)
ss.insert(0,1,'1');
for(int i=0;i<ss.length();i++)
{
m2[ss[i]]++;
}
if(m1==m2&&s.length()==ss.length())
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
cout<<ss;
return 0;
}