数据结构-起步能力自测题Have Fun with Numbers

 

自测-4 Have Fun with Numbers (20分)

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

大整数乘2运算 

一开始不知道数据到底会有多大,用Long long写了一下(还是不想用数组处理那种数据)

#include<iostream>
using namespace std;
int a[10];
int b[10];
int main()
{
	long long n;
	cin>>n;
	long long ans=n;
	while(n>0)
	{
		a[n%10]++;
		n/=10;
	}
	ans*=2;
	n=ans;
		while(n>0)
	{
		b[n%10]++;
		n/=10;
	}
	int flag=0;
	for(int i=0;i<10;i++)
	{
		if(a[i]!=b[i]) flag=1;
		//cout<<" "<<a[i]<<endl;
	}
	if(flag==0) cout<<"Yes"<<endl;
	else cout<<"No"<<endl;
	cout<<ans;
	return 0;
	
}

结果就是过了四个,有两个算例过不了,必须得处理大数。

一般情况下处理大数的乘法最好先进行倒置方便进位操作。

但是本题比较特殊,只涉及乘二的运算,如果有进位只会是1,可以直接判断是否进位输出1

进位通常是通过一个临时的tmp存乘2直接结果,然后结合一个up变量存进位值完成。

然后很多题解里面更加优秀的解法不是分别统计乘二前后的数字情况,而是在进行乘二操作的时候通过+ -直接操作一个count[]数组,最终数组全部置零就可以说明数字出现次数对应一致这种思路在很多算法题中都是可以用来进一步优化的方案。

最终AC代码:

#include<iostream>
#include<cstring>
using namespace std;
int digit[10];//存储各个原有数字出现的次数 
int main()
{
	char num[25];int up = 0;//up表示进位 
	cin>>num;
	for(int i = strlen(num)-1; i >= 0; i--){
		int tmp = num[i]-'0';
		digit[tmp]++;
		tmp = tmp*2 + up;
		up = 0;//进位置0
		if(tmp >= 10){
			tmp -= 10;
			up = 1;//进位置1
		} 
		num[i] = tmp + '0';
		digit[tmp]--; 
	}
	int flag = 0;
	for(int i = 0; i < 10; i++){
		if(digit[i] != 0) flag = 1;
	}
	if(up==1 || flag==1) cout<<"No"<<endl;
	else cout<<"Yes"<<endl;
	if(up == 1) cout<<"1";
	cout<<num;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值