PAT(甲)1023 Have Fun with Numbers (20)(详解)

1023 Have Fun with Numbers (20)(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.


  • 输入格式
    Each input file contains one test case. Each case contains one positive integer with no more than 20 digits.

  • 输出格式
    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.


题目大意:
这道题目主要是判断是否一个数字在乘以2之后,他的结果是否仍然为原来数字的组合,比如说
22*2=44,显然,原来的数字是2个2的组合,而结果是2个4的组合,不一样,因此输出No。

解题方法:
这道题目在解题上没有难度,直接把输入的数字用char数组存储,然后从数组的末尾开始,做乘法,不过需要考虑进位的问题,具体可以看我代码。


易错点:
1. 不要漏了最后一个进位,如999只用for循环会漏掉1998中的1


程序:

#include <stdio.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    char num[21];
    int douNum[22], check[10] = {0};
    int douIdx = 0, res, add = 0, flag = 0;     
    scanf("%s",num);    /* 输入测试样例 */
    for (int i = strlen(num) - 1; i >= 0; i--)
    {   
        res = (num[i]-'0') * 2 + add;
        if (res >= 10)
        {   
            res %= 10;
            add = 1;    /* 进位置1 */
        }
        else
            add = 0;    /* 进位置0 */
        douNum[douIdx++] = res;
    }
    if (add == 1)   /* 如果有36进位比如(9->18) */
        douNum[douIdx++] = 1;
    for (int i = 0; i < douIdx; i++)
        check[douNum[i]]++;     /* 对应数字出现次数+1 */
    for (int i = 0; i < strlen(num); i++)
        check[num[i]-'0']--;        /* 对应数字剩余出现次数-1 */
    for (int i = 0; i < 10; i++)
        if (check[i] != 0)  /* 如果出现该数字出现次数不相同 */
        {
            flag = 1;
            break;
        }
    if (flag == 1)
        printf("No\n");
    else
        printf("Yes\n");
    for (int i = douIdx-1; i >= 0; i--)
            printf("%d", douNum[i]);
    return 0;
}

如果对您有帮助,帮忙点个小拇指呗~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章