PAT(Advanced) 1023 Have Fun with Numbers C++实现

PAT(Advanced) 1023 Have Fun with Numbers C++实现

题目链接

1023 Have Fun with Numbers

题目大意

给定数值,判断其翻倍后组成的数字序列与原数值组成的数字序列是否一致,组成数字的顺序可以改变但各个数字的个数不能改变

算法思路

由于数值比较大,需采用字符串进行存储和计算,记录原来数字的序列组成并计数,再与翻倍后的数字序列组成对比即可

AC代码

/*
author : eclipse
email  : eclipsecs@qq.com
time   : Wed Jan 27 17:42:21 2021
*/
#include <bits/stdc++.h>
using namespace std;string doubleNumber(string number) {string doubledNumber = number;int carry = 0;for (int i = number.size() - 1; i >= 0; i--) {int result = number[i] - '0' + doubledNumber[i] - '0' + carry;carry = result / 10;result %= 10;doubledNumber[i] = '0' + result;}if (carry) {doubledNumber = char('0' + carry) + doubledNumber;}return doubledNumber;
}bool fun(string number, string doubledNumber) {vector<int> tag(10);for (int i = 0; i < number.size(); i++) {tag[number[i] - '0']++;}for (int i = 0; i < doubledNumber.size(); i++) {tag[doubledNumber[i] - '0']--;}for (int i = 0; i < tag.size(); i++) {if (tag[i]) {return false;}}return true;
}int main(int argc, char const *argv[]) {string number;cin >> number;string doubledNumber;doubledNumber = doubleNumber(number);printf("%s\n", fun(number, doubledNumber) ? "Yes" : "No");cout << doubledNumber;return 0;
}

样例输入

1234567899

样例输出

Yes
2469135798

鸣谢

PAT

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!