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