[PAT A1023]Have Fun with Numbers

[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.

输入格式

Each input contains one test case. Each case contains one positive integer with no more than 20 digits.

输出格式

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.

输入样例

1234567899

输出样例

Yes

2469135798

解析

  1. 这道题目的大致意思是,给你一个不超过20位的数,我们将它乘以2之后,得到一个数,并检验该数是否仍然还是由原先的各个数字组成,举个例子,1234567899*2=2469135798,发现2469135798的所有数字都在1234567899中出现且对于每个数字仅出现过相同的次数。
  2. 首先这个整数不超过20位,那么肯定是大整数乘法了,就连long long最多也只能支持17位(long long最大数有19位,但是不代表他能操作19位的数而不出错,有的19位的数乘以2后就超出long long的表示范畴了)
  3. 既然是大整数运算,相比除法就要简单很多了,这里就不赘述了,至于判断是否满足条件,我是使用了一个散列来运算的,这里仅供参考。
#include<iostream>
#include<string>
using namespace std;
struct bign
{
	int bit[25]; //虽然只有20位,这里开大一点,保险起见
	int len;
	bign() {
		len = 0;
	}
};
int hashTable[10] = { 0 };  //散列
int main()
{
	bign num, ans;
	string str;
	cin >> str;
	int j = 0;
	for (int i = str.length() - 1; i >= 0; i--) {
		num.bit[j++] = str[i] - '0';
		hashTable[str[i] - '0']++;  //每一个数字出现就该对应散列位置+1
		num.len++;
	}
	int carry = 0;  //存放进位
	for (int i = 0; i < num.len; i++) {
		ans.bit[i] = num.bit[i] * 2 + carry;
		if (ans.bit[i] >= 10) {
			ans.bit[i] -= 10;
			carry = 1;
			hashTable[ans.bit[i]]--; //得到一个数,就使得对应散列位置-1
		}
		else {
			carry = 0;
			hashTable[ans.bit[i]]--;
		}
	}
	if (carry == 1) {   //出现乘以二后位数不相等的情况
		ans.len = num.len + 1;
		ans.bit[ans.len - 1] = 1;
		hashTable[1]--;
	}
	else ans.len = num.len;
	bool judge = true;  //判断,若散列全为0,那么就满足条件
	for (int i = 0; i < 10; i++) {
		if (hashTable[i]) judge = false;
	}
	if (judge) printf("Yes\n");
	else printf("No\n");
	for (int i = ans.len-1; i >=0; i--) printf("%d", ans.bit[i]);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值