uva 11121 Base -2 (负进制计算)

题意:给一个数n,转换为-2进制的数。


解析:因为转换后的每一位数不能为负数,所以考虑如何将每次取模后的负数变为正数,且数为多少。

          结论是若取模为负,则加上基数的绝对值,当前的n++。

          设当前取模的位 t = n % base (t  < 0, base < 0)

          当 t - base(t + |base|)计入转换后的数中时, 原数的这个位相当于由 t * base ^ i 变为了 (t - base) * base ^ i。

          减少了需要回加,恰好当前n的值+1 = 原n值回加了base^(i + 1)。


代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long

using namespace std;
const int maxn = 1e5 + 10;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = 4 * atan(1.0);
const double ee = exp(1.0);

int num[maxn];
int n;
int top;
const int base = -2;

void miner_change()
{
    if (n == 0)
    {
        printf("0\n");
        return;
    }
    top = 0;
    while (n)
    {
        int t = n % base;
        n /= base;
        if (t < 0)
        {
            t -= base;
            n++;
        }
        num[top++] = t;
    }
}

int main()
{
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
#endif // LOCAL
    int ncase;
    scanf("%d", &ncase);
    int ca = 1;
    while (ncase--)
    {
        scanf("%d", &n);
        printf("Case #%d: ", ca++);
        miner_change();
        while (top)
        {
            int t = num[--top];
            printf("%d", t);
        }
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值