PAT1023: Have Fun with Numbers

1023. Have Fun with Numbers (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
1234567899
Sample Output:
Yes
2469135798

思路

Yes的满足条件:
输入的数before的所有位数字的计数与乘2以后得到的数after所有位数字的计数相同。

反之,No的满足条件:
1.after位数比before更大
2.after中并不能找到before的所有数字
3.after和before的相同数字的个数不一致。

所以,在位数相同的情况下,为了提高查找效率,还是用map模拟一个字典dic存放before的数字并计数,然后通过after的数字找到dic的数字,令其对应计数-1。
最后遍历dic,判断对应数字的计数是否仍为0即可。

代码
#include<iostream>
#include<iterator>
#include<map>
using namespace std;
int main()
{
  string before;
  while(cin >> before)
  {
      bool check = true;
      string after;
      int add = 0;

      for(int i = before.size() - 1;i >=0;i--)
      {
         int cur = (before[i] - '0') * 2 + add;
         add = cur / 10;
         cur = cur % 10;
         after.insert(0,to_string(cur));

         if(i == 0 && add == 1)
         {
          after.insert(0,to_string(add));
          check = false;
         }


      }
      map<char,int> dic;
      for(int i = 0; i < before.size();i++)
      {
         if(dic.count(before[i]) > 0)
            dic[before[i]]++;
         else
            dic.insert(pair<char,int>(before[i],1));
      }
      for(int i = 0;i < after.size();i++ )
      {
         if(dic.count(after[i]) > 0)
            dic[after[i]]--;
      }
      for(map<char,int>:: iterator it = dic.begin(); it != dic.end();it++)
      {
         if(it->second != 0)
         {
             check = false;
             break;
         }
      }

      if(check)
        cout << "Yes" << endl;
      else
        cout << "No" << endl;
      cout << after << endl;
  }
}

 

 

提交代码

posted @ 2017-10-05 16:33  0kk470  阅读(259)  评论(0编辑  收藏  举报