题意:设定一个数字,如果它只由2、3、6构成,则称它为happy数,题目要求从升序的1-n排列里,找到指定的第n个happy数,输出它的值。
分析:每个范围内的happy数个数是可以划分确定下来的,一位数范围内有3个,两位数范围内3+9个,三位数范围内3+9+27个……以此类推。2-6,22-66,222-666,2222-6666,每次都以n位2开始,以n位6结束,求第n个happy数的位置,我们可以先算出前面满层的层次个数 ans = pow(3, len) - 3 / 2,可以推出第n个happy数有几位(len),在2……2(len位)到6……6(len位)之间就是第 n-ans 个(如果刚好满层 n == ans,就直接输出 len 位 6 ),然后写出几个例子可以发现,这个happy数的每一位都可以推出来。
一开始读题读错了,以为求1-n中一共有几个happy数,浪费了不少时间,其实仔细看一下样例就知道 n = 680,怎么可能答案比输入还大…
accode:
#include <bits/stdc++.h>
#define ios std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
using namespace std;
typedef long long ll;
const int maxn = 1e5;
int main()
{
ios
int n;
cin>>n;
int len = 0;
int ans = 0;
for(int i = 1; ; i++)
{
ans = (pow(3, i) - 3) / 2;
if(ans == n)
{
len = i;
for(int i = 1; i < len; i++)
{
printf("6");
}
printf("\n");
return 0;
}
if(ans > n)
{
len = i - 1;
ans = (pow(3, i - 1)-3) / 2;
break;
}
}
int cc = n - ans;
for(int i = 1; i <= len; i++)
{
if(cc <= (pow(3, len-i)))
cout<<"2";
else if(cc <= (pow(3, len-i)*2))
{
cout<<"3";
cc -= pow(3, len-i);
}
else{
cout<<"6";
cc -= (2 * pow(3, len-i));
}
}
return 0;
}