Timus - 1209 - 1, 10, 100, 1000...
先上题目:
1209. 1, 10, 100, 1000...
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 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 ≤ 231 − 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 |
题意:按照1,10,100,1000```的顺序将数字排在一起,从左往右,(10^i)<=(2^31-1),问第k位是0还是1。
有人可以推出公式直接求第k位是0还是1,但是这里我用的方法不一样,首先我们可以得出第x个1出现的位置会是哪里:(x-1)*x/2+1=k,如果k符合这个条件就说明第k位是一个1否则就是0。不过如果枚举x来找k的话一定会超时,所以我们可以二分查找把x找出来,如果可以找出x说明是1,否则就是0了。
上代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #define LL long long 5 using namespace std; 6 7 int check(LL k){ 8 LL up=(1LL<<31)-1; 9 LL down=1; 10 LL mid; 11 LL m; 12 while(up>=down){ 13 mid=(up+down)/2; 14 m=mid*(mid-1)/2+1; 15 if(m==k) return 1; 16 else if(m>k) up=mid-1; 17 else down=mid+1; 18 } 19 return 0; 20 } 21 22 23 int main() 24 { 25 int n,k; 26 //freopen("data.txt","r",stdin); 27 scanf("%d",&n); 28 for(int i=0;i<n;i++){ 29 scanf("%d",&k); 30 if(i) printf(" "); 31 printf("%d",check(k)); 32 } 33 printf("\n"); 34 return 0; 35 }