题目描述
Michael要给自己的一本已经完成的书编上页码。众所周知,第一页页码是1,第二页页码是2,第三页页码是 3,……。而Michael敲一次键盘就能打出一个数字,例如打出1需要敲一次键盘,打出10需要敲两次键盘。页码编完之后,Michael记得自己总共敲了 n次键盘,问Michael的书有多少页。
输入
输入的第一行是整数T(0 < T <= 100),表示测试数据的组数。每一组测试数据只有一行,只有一个整数n(1 <= n <= 1000),表示Michael敲了n次键盘。该行没有其它多余的符号。
输出
如果有解,则输出书的页数。如果无解,输出-1。
样例输入
3
4
10
11
注意输入的是我们敲击键盘的数,不是页码数,不要看错题目了。
页码为99的时候,我们需要敲击键盘9+90*2=189次,这是分割条件。
敲击一次直接输出(1-9);敲击两次为一页,除以2(10-99);敲击三次为一页,除以3(100-999)。
下AC代码,供参考
1.将算式计算来的做比较,页码数肯定是整数。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int pnumber(int n) //page number(用来计算页码数);传入敲击键盘的数目
{
double sum; //通过算式计算出来的页码数
int res; //实际的页码数
if(n>0 && n<10)
{
return n;
}
else if(n>9 && n<=189)
{
sum=9+(n-9)/2.0;
if((int)sum==sum)
{
res=(int)sum;
return res;
}
else
{
return -1;
}
}
else if(n>189 && n<=1000)
{
sum=99+(n-189)/3.0;
if((int)sum==sum)
{
res=(int)sum;
return res;
}
else
{
return -1;
}
}
else
{
return 0;
}
}
int main()
{
int T;
int n;
while(cin>>T)
{
while(T--)
{
cin>>n;
cout<<pnumber(n)<<endl;
}
}
return 0;
}
2.直接将满足条件的和不满足条件的分开。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
int T;
int n;
cin>>T;
while(T--)
{
cin>>n;
if(n>=1 && n<=9)
{
cout<<n<<endl;
}
else if((n>9 && n<=189 && n%2==0)||(n>189 && n%3!=0))
{
cout<<"-1"<<endl;
}
else if(n>9 && n<=189 && n%2!=0)
{
n=9+(n-9)/2;
cout<<n<<endl;
}
else if(n>189 && n%3==0)
{
n=99+(n-189)/3;
cout<<n<<endl;
}
}
return 0;
}