题目
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;
}