【C/C++】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


题目源于https://pintia.cn/problem-sets/17/problems/263

题意解读:输入一个数字X,X乘以2后得到的数字Y,如果Y就是X的各位上的数字重新排列后的结果,则输出YES,否则输出NO.

重点!!! 因为输入样例最大不超过20位 ,而最大的long long 却仅有  2^64 = 1.844674407371 * 10  19,故需使用字符串来输入数字

// HaveFunWthNumbersPRO.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
	string str;
	int a[10] = { 0 }, b[10] = { 0 };	//用于记录0~9数字的个数
	vector<int> DoubleNum;				//用于最后输出乘2的数字
	cin >> str;							//输入一个字符串
	int length = str.length();			//获取字符串长度

	//区间 [0,length)
	for (int i = 0; i < length; i++) {	//记录输入字符串数字的个数
		int num = str[i] - '0';
		a[num]++;
	}
	int carry=0;									//进位数
	//区间[0,length),逆序从高向低
	for (int i = length - 1; i >= 0; i--)			//记录翻倍后字符串数字的个数
	{
		int num = (str[i] - '0') *2 + carry;		//按位计算先乘2再上进位数
		if (num >= 10) carry = 1;					//如果得到的num大于10则将进位数置为1
		else carry = 0;
		int remainder = num % 10;					//余数
		b[remainder]++;
		//向数组尾部插入remainder
		DoubleNum.push_back(remainder);
	}
	if (carry==1)	DoubleNum.push_back(1);       //!!!如果没有这一句,如果最高位发生进位,最高位会丢失!
	bool judge = true;
	//区间[0,10)
	for (int i = 0; i < 10; i++) {					//判断##原字符串的各位上的数字的个数和##成倍后的字符串的数字的个数是否相等
		if (a[i] != b[i]) {
			judge = false;
			break;
		}
	}
	if (judge) cout << "Yes" << endl;				//判断the numbers whether have fun with each other!
	else cout << "No" << endl;
	//区间[0,length)
	int size = DoubleNum.size();
	for (int i = size - 1; i >= 0; i--) {			//输出乘2后的数字
		cout << DoubleNum[i];
	}

	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值