Hex conversion (positive, negative)

Title Portal

The main idea of ​​the question:
give you a decimal number n (may be less than 0), let you convert to r-number (r may also be less than 0).

If n and r are both greater than 0, it is a good idea to save each bit directly by short division.
Short division

    int cnt=0;
    while(n)
    {
        a[cnt++]=n%r;
        n/=r;
    }

However, here, we cannot do this, because modulo a negative number may get a negative number, such as -15% -2 ==-1, -15 / -2 == 7. We must make the remainder positive to be a bit of a new hexadecimal number. Suppose the dividend is n, the divisor is r, the quotient is s, and the remainder is m.
Then there is n = s * r + m . When m is less than 0, we only need (+/-) r to make the remainder positive. At the same time, s also needs to be changed. See r for specific addition and subtraction. symbol.
Here we r is a negative point of view, if we want the remainder becomes positive, then to a minus r, set up a new business is x, then the n-the X-* = r + (mr) , very easy to find, the X- rr = s r ; so x = s + 1 .

Code on

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
const int inf=0x7fffffff;
const int mod=1e9+7;
const int eps=1e-6;
typedef long long ll;
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define pii pair<int,int>
//#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl '\n'
void add(string &s,int tt)
{
    if(tt<10)
        s+=tt+'0';
    else
        s+=tt-10+'A';
}
signed main()
{
    IOS;
    int n,r;
    cin>>n>>r;
    string s;
    int m=n;
    while(n)
    {
        if(n%r<0)
        {
            int tt=n%r-r;
            add(s,tt);
            n=n/r+1;
        }
        else
        {
            add(s,n%r);
            n/=r;
        }
    }
    reverse(s.begin(),s.end());
    cout<<m<<'=';
    for(int i=0;i<s.size();i++)
        cout<<s[i];
    cout<<"(base"<<r<<')';
}

Published 93 original articles · won praise 9 · views 4203

Guess you like

Origin blog.csdn.net/Joker_He/article/details/104784349