1023 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
题意:
将一个数字翻倍后,判断该数字是不是原来数字的重新排列。
思路:
大数加法。
Code:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 int main() { 6 string s; 7 cin >> s; 8 int len = s.length(); 9 int carry = 0; 10 map<int, int> m; 11 for (int i = 0; i < s.length(); ++i) m[s[i] - '0']++; 12 for (int i = len - 1; i >= 0; --i) { 13 s[i] += s[i] + carry - '0'; 14 carry = 0; 15 if (s[i] > '9') { 16 s[i] -= 10; 17 carry = 1; 18 } 19 } 20 if (carry == 1) s = '1' + s; 21 int flag = 0; 22 for (int i = 0; i < s.length(); ++i) 23 if (m[s[i] - '0'] > 0) 24 m[s[i] - '0']--; 25 else 26 flag = 1; 27 if (flag == 0) 28 cout << "Yes" << endl; 29 else 30 cout << "No" << endl; 31 cout << s << endl; 32 return 0; 33 }