1209. 1, 10, 100, 1000...Time Limit: 1.0 second
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.InputThere 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).OutputYou 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 |
431476 |
0 0 1 0 |
Problem Author: Alexey Lakhtin
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;}收穫:解決問題時,有時需要進一步思考。
參考:[1]:http://acm.timus.ru/problem.aspx?space=1&num=1209[2]:http://www.cnblogs.com/skyivben/archive/2009/03/14/1411282.html