1962. Hide That Number
单点时限: 2.0 sec
内存限制: 256 MB
According to Wikipedia, Cryptography is “the practice and study of hiding information” and this is exactly what Alex is looking for. Ever since he was a kid, Alex was paranoid over someone laying their hands on his phone book. He decided that he must write the numbers in some secret way that only he can decipher. At first he tried quite complex algorithms, but that slowed him down when he needed to dial a number fast. He finally came up with the following algorithm: Rather than writing down the number itself, Alex would shift the number one place to the left (as if multiplying it by 10,) then adding the shifted number to the original. For example, if the phone number was 123, Alex would add 1230 to it, resulting in 1353. To make what he writes looks as a regular phone number, Alex truncates the result (from the left,) so that it has as many digits as the original phone number. In this example, Alex writes 353 instead of 123 in his phone book.
Alex needs a program to print the original phone number given what is written in his phone book. Alex, who by the way is a good friend of Johnny, isn’t that good in arithmetic. It is quite possible that the numbers are messed up. The program should print “IMPOSSIBLE” (without the quotes) if the original number cannot be computed.
输入格式
Your program will be tested on one or more test cases. Each case is specified on a separate line and is made of a single positive number having less than 1,000,000 digits.
The last line of the input file is made of a single zero.
输出格式
For each test case, output the result on a single line using the following format:
k. result
Where k is the test case number (starting at 1).
样例
input
353
9988
123456
0
output
1. 123
2. IMPOSSIBLE
3. 738496
第一版,没考虑到12是可以有92*10+92=1012截取后面两位得到,但是改成下面前面加上2位数字,且不能为11,即可AC
#include<iostream>
using namespace std;
int getReminder(string s,int x,string &ans){
int reminder=0,flag=1;
for(int i=0;i<s.size();i++){
int tmp=reminder*10+s[i]-'0';
if(flag==0||tmp/x!=0){
ans+=to_string(tmp/x);
flag=0;
}
reminder=tmp%x;
}
if(ans.size()==0)ans="0";
return reminder;
}
int main(){
string s;
int cnt=1;
while(1){
cin>>s;
if(s=="0")break;
int ispossible=0;
for(int i=1;i<20;i++){
if(i==11)continue;
string tmp=to_string(i)+s,ans;
int rem = getReminder(tmp,11,ans);
if(rem==0){
cout<<cnt<<". "<<ans<<endl;
ispossible=1;
break;
}
}
if(ispossible==0)cout<<cnt<<". IMPOSSIBLE"<<endl;
cnt++;
}
}
第二版,选择从后往前处理,一开始由于ans=to_string(need)+ans
每次会创建新对象,导致超时。由于目标值长度已确定,所以通过填写每一位的数字即可,感觉也可以ans+=to_string(need)
,然后通过reverse函数反转一下ans
来解决。
#include<iostream>
using namespace std;
int main(){
int cnt=0;
string s;
while(1){
cin>>s;
cnt++;
if(s=="0")break;
printf("%d. ",cnt);
string ans;
ans.resize(s.size());
int need=0,carry=0;
for(int i=s.size()-1;i>=0;i--){
need=s[i]-'0'-need-carry;
if(need<0){
need+=10;
carry=1;
}else carry=0;
ans[i]=need+'0';
}
if(need==0)cout<<"IMPOSSIBLE"<<endl;
else cout<<ans<<endl;
}
}