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.
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
参考代码:
1 /*********************************************** 2 PAT A1023 Have Fun with Numbers 3 ***********************************************/ 4 #include <iostream> 5 #include <string> 6 #include <stack> 7 #include <map> 8 9 using namespace std; 10 11 int main() { 12 string num; 13 stack<int> numList; 14 stack<int> doubleList; 15 map<int, int> baseList; 16 17 cin >> num; 18 19 for (int i = 0; i < num.size(); ++i) { 20 numList.push(num[i] - '0'); 21 baseList[num[i] - '0']++; 22 } 23 24 int carry = 0, here = 0; 25 while (!numList.empty()) { 26 int n = numList.top(); 27 here = (n * 2) % 10 + carry; 28 carry = (n * 2) / 10; 29 doubleList.push(here); 30 numList.pop(); 31 32 baseList[here]--; 33 } 34 35 if (carry != 0) { 36 doubleList.push(carry); 37 baseList[carry]--; 38 } 39 40 bool withTheProperty = true; 41 for (map<int, int>::iterator it = baseList.begin(); it != baseList.end(); ++it) { 42 if (it->second != 0) { 43 withTheProperty = false; 44 break; 45 } 46 } 47 48 cout << (withTheProperty ? "Yes" : "No") << endl; 49 50 while (!doubleList.empty()) { 51 cout << doubleList.top(); 52 doubleList.pop(); 53 } 54 55 return 0; 56 }
注意事项:
1:输入的“正数”已经超过了long long的表示范围,采用string存储再做处理比较恰当。
2:输入的“正数” 翻倍之后可能会出现首位仍需进位的情况,因此需要判断一下进位值carry是否为0,如果不为0需要增加空间来存储carry。
3:这里采用stack是因为它FILO的特性符合我们从最低位开始翻倍,最后栈内元素出栈的顺序正好就是结果的顺序。当然也可以采用string等其它容器进行处理。