以负数为基数的进制怎么处理

 

C - Base -2 Number


Time Limit: 2 sec / Memory Limit: 1024 MB

Score : 300300 points

Problem Statement

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

Here, SS is the base −2−2 representation of NN when the following are all satisfied:

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

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

Constraints

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

Input

Input is given from Standard Input in the following format:

NN

Output

Print the base −2−2 representation of NN.


Sample Input 1 Copy

Copy

-9

Sample Output 1 Copy

Copy

1011

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


Sample Input 2 Copy

Copy

123456789

Sample Output 2 Copy

Copy

11000101011001101110100010101

Sample Input 3 Copy

Copy

0

Sample Output 3 Copy

Copy

0

#include<bits/stdc++.h>
using namespace std;
int mod(int n, int k){
    if(n%k < 0)
        return n-(n/k+1)*k;
    else
        return n%k;
}
int main()
{
    int n;int flag = 0;
    cin>>n;
    if(n==0){
        cout<<"0"<<endl;
        return 0;
    }
    string ans = "";
    int k = -2 ;
    while(n)
    {
        char a = mod(n,k) + '0';
        ans = ans + a;
        if(n%k < 0)
            n = n/k+1;
        else
            n /= k;
    }
    reverse(ans.begin(), ans.end());
    cout<<ans<<endl;
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值