1023 Have Fun with Numbers

来源:互联网 发布:mysql更新语句 编辑:程序博客网 时间:2024/05/17 08:37

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
解题思路:一开始记录各个数字出现的次数,然后double一下,看原先的数字是否够新的数字的组成。

#include<iostream>#include<string>#include<algorithm>#include<stdio.h>using namespace std;int main(){    for (string ss; cin >> ss;){        int flag[10] = { 0 };        for (int i = 0; i < ss.length(); i++){            flag[ss[i] - '0'] ++;        }        reverse(ss.begin(), ss.end());        string double_s = "";        int carry = 0;        for (int i = 0; i < ss.length(); i++){              double_s = double_s + (char)(((ss[i] - '0') * 2 + carry) % 10 + '0');            carry = ((ss[i] - '0') * 2 + carry) / 10;        }        if (carry){            double_s += (char)(carry + '0');        }        reverse(double_s.begin(), double_s.end());        int test = 1;        for (int i = 0; i < double_s.length(); i++){            if (flag[double_s[i] - '0']){                flag[double_s[i] - '0']--;            }            else{                test = 0;                break;            }        }        if (test){            printf("Yes\n");            cout << double_s << endl;        }        else{            printf("No\n");            cout << double_s << endl;        }    }    return 0;}
0 0
原创粉丝点击