【C/C++】Have Fun with Numbers

来源:互联网 发布:算法分析的两个方面 编辑:程序博客网 时间:2024/05/22 03:27

自测-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:

Yes2469135798


题目源于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则将进位数置为1else carry = 0;int remainder = num % 10;//余数b[remainder]++;//向数组尾部插入remainderDoubleNum.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;}