PAT 1023 Have Fun with Numbers(簡單計數+大整數)

題目

https://www.patest.cn/contests/pat-a-practise/1023

題意:輸入一串不超過20位的數字,將該數字串乘以兩倍後,判斷新數串是否爲原數串的一個排列。

解題思路

統計舊字符串中數字0-9的出現次數和新字符串中數字0-9的出現次數,若兩者完全相同,則新數串是原數串的一個排列。

AC代碼

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[25];
    cin >> str;
    int s[25], index = 0;
    int old_cnt[10] = {0};
    for (int i = strlen(str)-1; i >= 0; --i)
    {
        s[index++] = str[i]-'0'; //store digits inversely
        old_cnt[str[i]-'0']++; //count each digit
    }
    //double
    int res[25] = {0}, new_cnt[10] = {0}, tmp;
    for (int i = 0; i < index; ++i)
    {
        tmp = s[i] << 1;
        res[i] += tmp%10;
        res[i+1] += tmp/10;
    }
    if (res[index] != 0)
        new_cnt[res[index]]++;
    for (int i = 0; i <= index; ++i)
    {
        if (i != index)
            new_cnt[res[i]]++;
        else if (res[index] != 0)
            new_cnt[res[index]]++;
    }
    //check
    bool flag = true;
    for (int i = 0; i <= 9; ++i)
    {
        if (old_cnt[i] != new_cnt[i])
        {
            flag = false;
            break;
        }
    }
    if (flag) cout << "Yes" << endl;
    else cout << "No" << endl;
    for (int i = index; i>=0; --i)
    {
        if (i == index && res[index] == 0) //leading digit is zero
            continue;
        cout << res[i];
    }
    cout << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章