1209. 1, 10, 100, 1000...
Time Limit: 1.0 second
Memory Limit: 16 MB
Memory Limit: 16 MB
Let's consider an infinite sequence of digits constructed of ascending powers of 10 written one after another. Here is the beginning of the sequence: 110100100010000… You are to find out what digit is located at the definite position of the sequence.
Input
There is the only integer N in the first line (1 ≤ N ≤ 65535). The i-th of N left lines contains the integer Ki — the number of position in the sequence
(1 ≤
Ki ≤ 2
31 − 1)
.
Output
You are to output N digits 0 or 1 separated with a space. More precisely, the i-th digit of output is to be equal to the Ki-th digit of described above sequence.
Sample
input | output |
---|---|
4
3
14
7
6
| 0 0 1 0
|
Problem Author: Alexey Lakhtin
Problem Source: USU Open Collegiate Programming Contest October'2002 Junior Session
Problem Source: USU Open Collegiate Programming Contest October'2002 Junior Session
Solution
序列由10的自然数次幂连接而成,即1 10 100 1000......
数组的位置0 1 3 6 10......处为1,即x=0+1+2+3+...+n时结果为1.
原始算法:
int judge(int x)
{
int i=0;
while(x>0)
{
x-=i;
++i;
}
if(x==0)
return 1;
else //if(x<0)
return 0;
}
提交后时间溢出。
进一步:
x=n(n+1)/2,解得n=(sqrt(8x+1)-1)/2,并由此判断输出。
最后代码:
#include <iostream>
using namespace std;
int judge(int x)
{
double n=(sqrt(8.0*x+1)-1)/2;
return (n==int(n))?1:0;
}
int main()
{
int N;
cin>>N;
int *arr=new int[N];
for(int i=0;i<N;++i)
cin>>arr[i];
for(int i=0;i<N;++i)
cout<<judge(arr[i]-1)<<' ';
delete []arr;
system("pause");
return 0;
}
收获:解决问题时,有时需要进一步思考。
参考: