PAT甲1023 Have Fun with Numbers multiset多重集合容器/字符串倒置/小学生加法/两set比较

本文介绍如何使用C++的多重集合(multiset)和竖式计算方法,判断一个大数double后其数字位顺序是否保持不变。通过实例展示了如何构造multiset并利用`equal`函数进行比较,适用于解决数字位数处理问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

题目

Sample Input

1234567899

Sample Output

Yes
2469135798

思路

题意大概是:请问一个很大的数double了以后,它的各位数字组成和原来是否一样

  • 用STL的多重集合容器multiset就可以实现,multiset允许集合中存在重复的元素
  • 由于数的位数最高可达20位,所以对字符串进行操作,用竖式计算的方法求double值
  • algorithm头文件中,有reverse函数可以实现字符串倒置,还有equal函数可以比较两个集合是否相等

参考:C++ 参考手册

/* reverse() 常用形式 */
//适用于数组和STL容器
template< class BidirIt >
void reverse( BidirIt first, BidirIt last );


/* equal()常用形式 */
//1
template< class InputIt1, class InputIt2 >
bool equal( InputIt1 first1, InputIt1 last1,
            InputIt2 first2, InputIt2 last2 );
            
//2
template< class InputIt1, class InputIt2 >
bool equal( InputIt1 first1, InputIt1 last1,
            InputIt2 first2 );
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>

/* eg. 使用equal判断回文串 */
void test(const std::string& s)
{
    if(std::equal(s.begin(), s.begin() + s.size()/2, s.rbegin())) {
        std::cout << "\"" << s << "\" is a palindrome\n";
    } else {
        std::cout << "\"" << s << "\" is not a palindrome\n";
    }
}

int main()
{
	/* eg. 使用equal判断回文串 */
    test("radar"); //"radar" is a palindrome
    test("hello"); //"hello" is not a palindrome

	/* eg. 使用reverse倒置数组和vector */
    std::vector<int> v{1,2,3};
    std::reverse(std::begin(v), std::end(v));
    for(auto e : v) std::cout << e;
    std::cout << '\n'; //321
 
    int a[] = {4, 5, 6, 7};
    std::reverse(std::begin(a), std::end(a));
    for(auto e : a) std::cout << e; //7654
}

AC代码

#include <bits/stdc++.h>
using namespace std;
/*
* 竖式计算实现自加
*/
string doubleStr(string& s){
    string res = "";
    int cur;     //当前位
    int jin = 0; //进位位
    for(int i = s.size()-1;i>=0;--i){
        cur = s[i]-'0';
        res.append(to_string((cur*2+jin)%10));
        jin = (cur*2+jin)/10;
    }
    if(jin>0)
        res.append(to_string(jin));
    reverse(res.begin(),res.end());//倒置结果字符串
    return res;
}

int main(){
	//Input
    string s;
    cin>>s;
    //构造multiset
    multiset<int> ori,dbl;
    for(int i = 0;i<s.size();++i){
        ori.insert(s[i]-'0');
    }
    string dbS = doubleStr(s);
    for(int i = 0;i<dbS.size();++i){
        dbl.insert(dbS[i]-'0');
    }
    //比较与Output
    bool isEqual = std::equal(ori.begin(), ori.end(), dbl.begin(), dbl.end());
    cout<<(isEqual?"Yes":"No")<<"\n"<<dbS;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值