Leetcode1256 加密数字(手动找规律)

刷b站无意间看到了这道题,于是心血来潮想了想,但是没有leetcode的会员交不了。。。

通过表可以发现:
第i位的 1 表示 2 * 2^i, 0 表示 1 * 2^i ,其中最低位为第0位。
那么我们把f(n)转化为2进制,1: 2 *2^i --> 2 *2^(i+1),即进位,0则不管;
那么 我们把2进制转化为f(n) ,可以通过从低位开始借位 得到答案;

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e6+5;;
const int inf=0x3f3f3f3f;
#define ls (i<<1)
#define rs (i<<1|1)
#define fi first
#define se second
#define mem(a,b) memset(a,b,sizeof(a))
LL read()
{
    LL x=0,t=1;
    char ch=getchar();
    while(!isdigit(ch)){ if(ch=='-')t=-1; ch=getchar(); }
    while(isdigit(ch)){ x=(x<<1)+(x<<3)+(ch^48); ch=getchar(); }
    return x*t;
}

int main()
{
    LL n;
    while(scanf("%lld",&n)!=EOF)
    {
        if(n==0)
        {
            printf("\n");
            continue;
        }
        int s[105],ans[105];
        mem(s,0); mem(ans,0);
        int tot=0;
        for(int i=0;(1<<i)<=n;i++)
            if(n&1<<i) s[i]=1,tot=i;
        for(int i=0;i<=tot;i++)
        {
            if(s[i]==1) ans[i]=0;
            else
            {
                s[i+1]--;
                ans[i]=++s[i];
                if(i+1==tot) tot--;
            }
        }
        for(int i=tot;i>=0;i--)
            printf("%d",ans[i]);
        putchar('\n');
    }
}

posted @ 2019-12-11 21:14  DeepJay  阅读(354)  评论(0编辑  收藏  举报