Atcode Base 2 - Number

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 0 and 1.
  • Unless S= 0, the initial character of S is 1.
  • Let S=Sk  Sk−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.
  • −10^9≤N≤10^9

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

 

 

 

#include <iostream>
#include <stack>
 
using namespace std;
 
int N;
 
int main(int argc, char** argv) {
    cin >> N;
    stack<int> s;
    while (N != 0) {
        int b = N % 4;
        if (b < -2) b += 4;
        if (1 < b) b -= 4;
        if (b == -2) {
            s.push(0);
            s.push(1);
        } else if (b == -1) {
            s.push(1);
            s.push(1);
        } else if (b == 0) {
            s.push(0);
            s.push(0);
        } else if (b == 1) {
            s.push(1);
            s.push(0);
        }
        N = (N - b) / 4;
    }
    if (s.empty()) {
        cout << 0;
    } else {
        if (s.top() != 0) {
            cout << 1;
        }
        s.pop();
        while (!s.empty()) {
            cout << s.top();
            s.pop();
        }
    }
    cout << endl;
}

 

#include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3f
#define EPS (1e-10)
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
 
signed main(){
	int n;cin>>n;
	string s;
	rep(i,40){
		if(n>>i&1){
			s+='1';
			if(i%2==0){
				n-=(1<<i);
			}
			else{
				n+=(1<<i);
			}
		}
		else s+='0';
	}
	while(!s.empty()&&s.back()=='0')s.pop_back();
	reverse(s.begin(),s.end());
	if(s.empty())s="0";
	cout<<s<<endl;
}

 

 

#include<bits/stdc++.h>
using namespace std;
const int N=100;
int main()
{
    int n,cnt=0,a[N];
    scanf("%d",&n);
    if(n==0){
        return 0*printf("0\n");
    }
    while(n){
        if(n&1){
            a[cnt++]=1;
            n=(n-1)/(-2);
        }else{
            a[cnt++]=0;
            n=n/(-2);
        }
    }
    for(int i=cnt-1;i>=0;i--){
        printf("%d",a[i]);
    }
    return 0;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值