自测-4 Have Fun with Numbers (20分)C++

用哈希表的思想。

题目给20位的整数很明显超过了2^64,一般对于很大的数据量,用string来代替int,还可以节省空间。
先编写一个double string的函数,注意进位和比原来字符串多一位就好。
然后对原字符串每一位,构造一个table,初始化10个0(表示0-9,table中的存的数据表示的是出现次数),然后分别对s 和doublestr(s)构造table比较就好了。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

string doublestr(string s)
{
    int carry = 0;
    for (int i = (int)s.size() - 1; i >= 0; i--)
    {
        char temp = s[i];
        s[i] = (carry + (s[i] - '0') * 2) % 10 + '0';
        carry = (carry + (temp - '0') * 2) / 10;
    }
    if (carry == 1)
    {
        s = "1" + s;
    }
    return s;
}


int main()
{
    //20位整数超过了整型范围,使用字符串吧
    string s1, s2;
    vector<int> table1(10, 0);
    vector<int> table2(10, 0);
    cin >> s1;
    for (auto a : s1)
    {
        table1[a - '0']++;
    }
    s2 = doublestr(s1);
    for (auto b : s2)
    {
        table2[b - '0']++;
    }
    if (table1 == table2)
    {
        cout << "Yes" << endl;
    }
    else
    {
        cout << "No"<< endl;
    }
    cout << s2;

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值