The number 666 is considered to be the occult “number of the beast” and is a well used number in all major apocalypse themed blockbuster movies. However the number 666 can’t always be used in the script so numbers such as 1666 are used instead. Let us call the numbers containing at least three contiguous sixes beastly numbers. The first few beastly numbers are 666, 1666, 2666, 3666, 4666, 5666…
Given a 1-based index n, your program should return the nth beastly number.
InputThe first line contains the number of test cases T (T ≤ 1,000).
Each of the following T lines contains an integer n (1 ≤ n ≤ 50,000,000) as a test case.
For each test case, your program should output the nth beastly number.
3 2 3 187
1666 2666 66666
题目大概:
输入n,找出第n大个含有666的数字。
思路:
这个题和基本的题型找出含有47的数字的数量差不多,这个是找出含有666的数字的数量。
但是这个题不是问的数量有多少,而是问的第n大个,那个数量已经固定了,只需要算出1到某个数含有666的数量最接近n的那个数是什么,即可。
也就是用一下二分,二分所有数,找出一个数量是小于n的最大的那个就行了。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
LL INF=0xfffffffffLL;
int a[22];
LL dp[22][2][2][2];
LL sove(int pos,int q1,int q2,int k,int limit)
{
if(pos==-1)return k;
if(!limit&&dp[pos][q1][q2][k]!=-1)return dp[pos][q1][q2][k];
int end=limit?a[pos]:9;
LL ans=0;
for(int i=0;i<=end;i++)
{
if(k==1)ans+=sove(pos-1,i==6,q1,1,limit&&i==end);
else ans+=sove(pos-1,i==6,q1,q1&&q2&&i==6,limit&&i==end);
}
if(!limit)dp[pos][q1][q2][k]=ans;
return ans;
}
LL go(LL x)
{
int pos=0;
while(x)
{
a[pos++]=x%10;
x/=10;
}
return sove(pos-1,0,0,0,1);
}
int main()
{ int t;
LL n;
memset(dp,-1,sizeof(dp));
scanf("%d",&t);
while(t--)
{
scanf("%I64d",&n);
LL l=1,r=INF,mid;
while(l<=r)
{
mid=(l+r)/2;
if(go(mid)<n)
{
l=mid+1;
}
else
{
r=mid-1;
}
}
printf("%I64d\n",l);
}
return 0;
}