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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值