[timus] 1209. 1, 10, 100, 1000…

來源:互聯網
上載者:User
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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.