1023. 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 file 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:1234567899Sample Output:
Yes2469135798
这题很简单啊,但是我能说我还写了一个小时才拿到满分了么?简直是要哭啊~.~
思路很简单,将读入的数据用字符串形式读出来,然后一位一位地进行处理,模拟我们在纸上做乘法的过程,主要是特别处理有进位时的情况即可;新建两个数组,存放每个数字出现的次数即可!下面是我的代码
#include<vector> #include <sstream> #include<cmath> #include<iomanip> #include<iostream> #include <ctype.h> #include <stdlib.h> #include <algorithm> using namespace std; int main() { string s; cin >> s; int num[11] = { 0 }; int nums[11] = { 0 }; vector<int> funums; int jinwei = 0; for (int i = s.length() - 1; i >= 0; i--)//做乘法的过程 { int digt = s[i] - '0'; num[digt]++; int temp = digt * 2; int gewei = temp % 10 + jinwei; funums.push_back(gewei); jinwei = temp / 10; } if (jinwei != 0)//注意处理最后一位的进位,也就是最高位,这里包含一个测试用例 funums.push_back(jinwei); for (int i = 0; i < funums.size(); i++) { nums[funums[i]]++; } int flag = 1; for (int i = 0; i < 11; i++)//判断两个数组中的内容是否相等即可 { if (nums[i] != num[i]) { cout << "No" << endl; for (int j = funums.size() - 1; j >= 0; j--) { cout << funums[j]; } flag = 0; break; } } if (flag == 1) { cout << "Yes" << endl; for (int j = funums.size() - 1; j >= 0; j--) { cout << funums[j]; } } return 0; } //备注:其实我原来用的是,两个数组保存乘积的结果,和原来的数组,再对他们进行排序,然后一一比较,最后有一个两分的测试用例没过,觉得用数组下标表示次数的方法会更简便一些,以后在使用的过程中要注意