题目链接: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
and1
. - Unless S=
0
, the initial character of S is1
. - 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;
}