您的位置:首页 > 其它

自测4. Have Fun with Numbers

2015-04-08 19:34 92 查看
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 file 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

//数组a用来存储输入数据中0-9的个数, b用来存储输出数据的0-9的个数
//k1,k2分别表示输入输出数据的长度,temp作为中间变量
int a[10]={0},b[10]={0},k1,k2,temp;
string s1,s2;	//存储输入输出数据
bool t=true;

while(cin>>s1)
{
k1=s1.length();
for(int i=0;i<k1;i++)
{
temp=s1[i]-48;//将字符串中的字符转为相应的整型数字
a[temp]++;	  //记录0-9的个数
}

s2=bigNumAdd(s1,s1);//调用大数加法函数,实现加倍运算
k2=s2.length();
for(int i=0;i<k2;i++)
{
temp=s2[i]-48;//将字符串中的字符转为相应的整型数字
b[temp]++;	  //记录0-9的个数
}

for(int i=0;i<=9;i++)//判断是否0-9的个数相同 并初始化数组
{
if(a[i]!=b[i])
t=false;
a[i]=0;
b[i]=0;
}

if(t)	//根据是否相同输出结果
cout<<"Yes"<<endl<<s2<<endl;
else
cout<<"No"<<endl<<s2<<endl;

t=true;
}


个人这道题的核心倒是大数的加法,因为20位数超出了整型数的范围

于是翻遍硬盘,找回以前的代码,下面献上大数加的核心代码:

string addBigNum(string s1,string s2)
{
int len1=s1.length(),len2=s2.length();//分别存储两个字符串的长度
int sum,remain,bit=0;//依次存储每次运算得到的和,余数,和进位的值;
string s="";//存储结果字符串

//先判断两个字符串的长度,习惯性把长的写在前面
if(s1.length()<s2.length())
swap(s1,s2);

//运算分为两部分,第一部分为两个字符串的共有部分,
for(int i=0;i<len2;i++)//从低位相加到共有部分的最高位
{
sum=s1[len1-1-i]-'0'+s2[len2-1-i]-'0'+bit;//对应位的数相加并加上进位
remain=sum%10;//取余
bit=sum/10;//查看是否有进位
s+=remain+'0';
}

//第二部分为长字符串独有部分,若无进位直接复制多出来的部分
for(int i=len2;i<len1;i++)
{
sum=s1[len1-i-1]-'0'+bit;//对应位的数相加并加上进位
remain=sum%10;//取余
bit=sum/10;//查看是否有进位
s+=remain+'0';
}
if(bit>0)//若最后仍有进位,则最高位加1
s+='1';
reverse(s.begin(),s.end());//倒置字符串
return s;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: