1023 Have Fun with Numbers

本文探讨了一种独特的数字属性,即某个数字翻倍后,其结果是否仅由原数字的数字重新排列组成。通过使用hashTable数组记录数字频率,实现了高效的大数乘法和数字排列检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1023 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


题型分类:字符串处理

题目大意:对输入的一串数字,加倍以后,查看新的一串数字是否是原来数字的排序。

解题思路:中心思想是模拟大数乘法运算。对于判断是否是原来数字的另一种排列,使用hashTable数组记录出现的数字的次数,原数字串出现一个数字,就让hashTable对应那个数字的值加一;新数字串出现一个数字,就让hashTable对应那个数字的值减一,最后判断hashTable里面的值是否为全0。


#include <iostream>
#include <cstdio>
#include <string>

using namespace std;

const int maxn = 25;

int hashTable[10]; //表示数字0-9出现的次数 
int num[maxn], doubleNum[maxn];

int main(int argc, char** argv) {
	string str;
	cin >> str;
	int carry = 0, len = 0;
	for(int i = str.length() - 1; i >= 0; i--, len++) {
		num[len] = str[i] - '0';
		doubleNum[len] = (carry + num[len] * 2) % 10;
		carry = (carry + num[len] * 2) / 10;
		hashTable[num[len]]++;
		hashTable[doubleNum[len]]--;
	}
	bool flag = false;
	for(int i = 0; i <= 9; i++){
		if(hashTable[i] != 0) flag = true;;
	}
	if(carry > 0){
		doubleNum[len++] = 1;
		flag = true; //位数都不相同了,就不可能是原始数字的排列了 
	}
	if(flag) printf("No\n");
	else printf("Yes\n");
	for(int i = len - 1; i >= 0; i--){
		printf("%d", doubleNum[i]);
	}
	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值