105.C - Base -2 Number

题目链接:https://abc105.contest.atcoder.jp/tasks/abc105_c

 

Time limit : 2sec / Memory limit : 1024MB

Score : 300 points

Problem Statement

Given an integer N, find the base −2 representation of N.

Here, S is the base −2 representation of N when the following are all satisfied:

  • S is a string consisting of 0 and 1.
  • Unless S0, the initial character of S is 1.
  • Let S=SkSk−1…S0, then S0×(−2)0+S1×(−2)1+…+Sk×(−2)k=N.

It can be proved that, for any integer M, the base −2 representation of M is uniquely determined.

Constraints

  • Every value in input is integer.
  • −109≤N≤109

Input

Input is given from Standard Input in the following format:

N

Output

Print the base −2 representation of N.


Sample Input 1

-9

Sample Output 1

1011

As (−2)^0+(−2)^1+(−2)^3=1+(−2)+(−8)=−9, 1011 is the base −2 representation of −9.


Sample Input 2

123456789

Sample Output 2

11000101011001101110100010101

Sample Input 3

0

Sample Output 3

0

分析:题目大致是让我们将一个整数(-1e9~1e9)转化为负二进制数。

而表达的时候是不会出现-1和0搭配的情况的如(-3)不是(-1-1),而是1101,而我们计算n对(-2)取余的时候是会出现-1的,因此我们要把这个-1变成正1。举个例子,对于-5转化为负二进制,第一步为 -5= (-2 )*2(2为商)+(-1),我们要把最后这个(-1)变为1,那么只有改变商,即-5=(-2)*(2+1)+1。此时就得到了我们要的1.

代码:

#include<cstring>
#include<cstdio>
#include<cmath>
int main()
{
    int n;
    int a[1000];
    int i = 0;
    scanf("%d", &n);
    if(n==0)
    {
        printf("0\n" );
        return 0;
    }
    while (n != 0 )    //短除法
         {

             a [ ++ i ] = n % (- 2 );

             n /= (- 2 );

             if (a [ i ] == - 1 )        //将余数为-1的改为1
             {
                a [ i ] = 1 ;
                n ++ ;            //(商)*(-2)-1 == (商+1)*(-2)+1
             }

        }
    for(int j = i; j >= 1;j--)printf("%d", a[j]);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值