大整数运算(二)(PAT)A1023.Have Fun with Numbers

题目描述:

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.

我的解题模板

代码:

#include<cstring>
#include<cstdio>
#include<iostream>
using namespace std;
/*************模板部分*************/
struct bign{
	int d[21];
	int len;
	bign(){
		memset(d,0,sizeof(d));
		len=0;
	}
};

bign change(char str[]){
	bign a;
	a.len=strlen(str);
	for(int i=0;i<a.len;i++){
		a.d[i]=str[a.len-i-1]-'0';
	}
	return a;
}

void print(bign a){
	for(int i=a.len-1;i>=0;i--){
		printf("%d",a.d[i]);
	}
}
/*************模板部分*************/
bign multi(bign a,int b){//高精度乘法
	bign c;
	int carry=0;//进位
	for(int i=0;i<a.len;i++){
		int temp=a.d[i]*b+carry;
		c.d[c.len++]=temp%10;//个位作为该位结果
		carry=temp/10;//高位部分作为新的进位
	}
	while(carry!=0){//和加法不一样,乘法的进位可能不止1位,因此用while
		c.d[c.len++]=carry%10;
		carry/=10;
	}

	return c;
}

bool Judge(bign a,bign b){//判断b的所有位是否是a的某个排列
	if(a.len!=b.len) return false;//若长度不等,则肯定是false
	int count[10]={0};//计数0~9出现的次数
	for(int i=0;i<a.len;i++){
		count[a.d[i]]++;//数位a.d[i]对应count值加1
		count[b.d[i]]--;//数位b.d[i]对应count值减1
	}
	for(int i=0;i<10;i++){//判断0~9的出现次数是否都为0
		if(count[i]!=0){//只要有一个数字的出现次数不为0,则返回false
			return false;
		}
	}
	return true;//返回true
}

int main(){
	char str[21];
	gets(str);//输入数据
	bign a=change(str);//转换为bign
	bign mul=multi(a,2);//计算a*2
	if(Judge(a,mul)==true)printf("Yes\n");
	else printf("No\n");
	print(mul);//输出结果
	system("pause");
	return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值