AtCoder Beginner Contest 105 C Base -2 Number 题解
AtCoder Beginner Contest 105 C Base -2 Number
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
0and1. - Unless S=
0, the initial character of S is1. - Let S=SkS**k−1…S0, then S0×(−2)0+S1×(−2)1+…+S**k×(−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
题解
题意
对于任意给出的数,给出其在-2进制中的表述方法。具体解释可以查看样例1的输入。
思路
其实本题就是考察对进制的理解。特别是对于负数进制,总结下负数进制的相关性质和操作:
负进位制有一个非常奇特的功能:它可以表示出负数但不需要用负号。一个负进制数可能是负数,也可能是正数。比如,负六进制下的12等于十进制下的-4,而负六进制下的123等于1(-6)2+2*(-6)1+3,即十进制下的27。是正是负取决于位数的奇偶:若该数有偶数位,则该数为负数;若有奇数位,则该数为正数。原因很简单,小数点每右移一位,相当于这个数乘以-6;从一位数开始,乘奇数次后该数的位数变成偶数且值为负,乘偶数次该数仍有奇数位且值仍为正。
由于末尾添0的性质(小数点移位的性质)仍然成立,负六进制与十进制的转换依然是上面的方法:(123)-6=(1(-6)+2)*(-6)+3=(27)10。十进制转负六进制:彻头彻尾的逆操作。找到最小的非负整数x使得当前数减x能被6整除,这个x将作为新的最高位写到结果中,然后当前数减去x再除以-6。
代码
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
#define REP(i,n) for(int i=0;i<(n);i++)
const int MAXN = 63;
int num[MAXN];
int main(){
int N =0;
scanf("%d",&N);
int tot = 0;
memset(num,0,sizeof(num));
if(N!=0){
while(N!=0){
if(N%2!=0){
num[tot++] = 1;
N = (N-1)/(-2);
}else{
num[tot++] = 0;
N = N/(-2);
}
//printf("%d %d\n",N,tot);
}
for(int i=tot-1;i>=0;i--){
printf("%d",num[i]);
}
printf("\n");
}else{
printf("0\n");
}
return 0;
}

浙公网安备 33010602011771号