poj2116

数论
需要细心,模拟过程就可以了,注意给出的字符串有前导0,需要去前导0

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int maxn = 50;
char s1[maxn],s2[maxn],s3[maxn];
LL f[maxn];

void init()
{
    f[0] = 1; f[1] = 2;
    for(int i = 2; i < maxn; i++) f[i] = f[i-1] + f[i-2];
}
LL calu(char s[])
{
    int len = strlen(s),cur = 0;
    LL res = 0;
    for(int i = len - 1; i >= 0; i--) res += (s[i] - '0')*f[cur++];
    return res;
}
bool isOK(char s[])
{
    bool OK = true;
    int len = strlen(s);
    for(int i = 1; i < len; i++) if( (s[i]-'0')&(s[i-1]-'0') == 1 ) OK = false;
    return OK;
}
void change(char s[])
{
    while(!isOK(s)) //s中一定存在连续的1
    {
        int index = strstr(s,"11") - s;
        s[index] = s[index + 1] = '0';
        if(index == 0)
        {
            int len = strlen(s);
            for(int i = len-1; i >= 0; i--) s[i+1] = s[i];
            s[len+1] = '\0';
            s[0] = '1';
        }
        else s[index-1] = '1';
    }
}
void trans(LL x,char s[])
{
    if(x == 0)
    {
        s[0] = '0'; s[1] = '\0'; return;
    }
    int cnt = 0,index = 0;
    while(x >= f[cnt]) cnt++;
    for(int i = cnt-1; i >= 0; i--)
    {
        if(x >= f[i])
        {
            x -= f[i]; s[index++] = '1';
        }
        else s[index++] = '0';
    }
}
void myremove(char s[])
{
    if(calu(s) == 0)
    {
        s[0] = '0'; s[1] = '\0'; return;
    }
    int len = 0;
    while(s[len] == '0') len++;
    int index = 0;
    for(int i = len; i < strlen(s); i++) s[index++] = s[i];
    s[index] = '\0';
}
int main()
{
    init();
    while(scanf("%s%s" ,s1,s2) != EOF)
    {
        myremove(s1);
        myremove(s2);
        LL x = calu(s1);
        LL y = calu(s2);
        LL z = x + y;
        change(s1);
        change(s2);
        trans(z,s3);
        change(s3);
        int len1 = strlen(s1);
        int len2 = strlen(s2);
        int len3 = strlen(s3);
        for(int i = 1; i <= len3+2-len1; i++) printf(" ");
        printf("%s\n",s1);
        printf("+");
        for(int i = 1; i <= len3+2-len2-1; i++) printf(" ");
        printf("%s\n",s2);
        printf("  ");
        for(int i = 1; i <= len3; i++) printf("-");
        printf("\n");
        printf("  ");
        printf("%s\n",s3);
        printf("\n");
        memset(s1,0,sizeof(s1));
        memset(s2,0,sizeof(s2));
        memset(s3,0,sizeof(s3));
    }
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值