There is a sequence of binary strings s0,s1,s2,…which can be defined by the following recurrence relation:
- s0=0
- si=s(i−1)+bi(i-1是下标,i也是)
Here bi means the binary form of i without leading zeros. For example, b5=101. And s(i−1)+bi means to append string bi to the back of s(i−1).
s0 | s1 | s2 | s3 | s4 | s5 | …… |
0 | 01 | 0110 | 011011 | 011011100 | 011011100101 | …… |
Let's use pk to denote the prefix of s(s的下标是10的100次方) of length k. Now given k, please calculate the length of the longest continuous 1 in pk.
Input
The first line of the input contains one integer T (1≤T≤1e4), indicating the number of test cases.
For each test case, the only line contains one integer k(1≤k≤1e9), indicating the length of the prefix.
Output
For each test case, output one integer in a single line, indicating the length of the longest continuous 1 in pk.
Examples
Inputcopy | Outputcopy |
---|---|
4 1 2 3 4 | 0 1 2 2 |
题目大意:
由0,1,2,3,4...的二进制数0,1,10,11,100...也就是b0,b1,b2,b3,b4拼接而成的字符串si=si-1+bi。现在求s(下标10的100次方)前k个字符中最长的1的个数。
找规律:
使用A数组来表示前i个区间的长度,a数组来表示第i个区间的长度。
则A[i] = A[i-1] + a[i]。
然后使用二分查找k在哪个区间上。假设在区间n上,则有n个最长连续1的个数为n(看图)
代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e6+10;
LL A[N],a[N];
LL t,k;
int main()
{
cin>>t;
a[0] = 1,a[1] = 1;
LL x=2;
//30是由最大数据得来
for(int i=2;i<=30;i++)
{
a[i] = x*pow(2,(x-1));
x++;
}
for(int i=0;i<30;i++)
{
A[i] = A[i-1] + a[i];
//cout<<A[i]<<endl;
}
while(t--)
{
cin>>k;
//区间范围就是 0-30
int l=0,r=30;
while(l<r)
{
int mid = l+r >> 1;
if( A[mid] >= k ) r = mid;
else l = mid + 1;
}
cout<<r<<endl;
}
return 0;
}