【题意】
输入一个不超20位的数字,计算其两倍的结果,然后判断其两倍的结果与初始数的各个数位,不同数字出现次数是否相同,然后再输出初始数两倍的结果。
PS:注意初始数long long(最多19位)可能也存不下20位的情况,int(最多10位)更不用说了;
【原题链接】
Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!
Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.
Input Specification:
Each input contains one test case. Each case contains one positive integer with no more than 20 digits.
Output Specification:
For each test case, first print in a line "Yes" if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or "No" if not. Then in the next line, print the doubled number.
Sample Input:
1234567899
Sample Output:
Yes
2469135798
【题解】
思路一:
用string读入,vector来后续处理及存储;设置一个变量t来处理进位;而各数位上不同数字的计数比较,可以通过排序后直接比较容器内值是否相同来实现;需要注意遍历、计算、输出过程中的正确位序。
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
string s;
cin>>s; //以字符串读入及存储
vector<int> a;
for(int i=s.size()-1;i>=0;i--){ //从低位到高位读入vevtor a,注意将字符转为数字(减去一个偏移量)
a.push_back(s[i]-'0');
}
vector<int> aa; //用aa来存两倍结果
int t=0,c;
for(int i=0;i<a.size();i++){
c=a[i]+a[i]+t; //t为进位数,0或1;
aa.push_back(c%10); //结果当前位读入
t=c/10; //存可能的进位
}
if(t) aa.push_back(t); //处理最后一位可能的进位
vector<int> b=aa; //复制vector aa到vector b (重排序后要输出原来的aa)
sort(a.begin(),a.end()); //通过重排序后vector的直接比较,可以判断各个数字的数目是否相同
sort(aa.begin(),aa.end());
if(aa==a) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
for(int i=b.size()-1;i>=0;i--){ //因为是将2倍的结果从低位到高位运算后直接存入,逆序输出结果,才是从高位到低位序
cout<<b[i];
}
return 0;
}