自测-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
// 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;
}