进制转换问题

发布于:2024-04-29 ⋅ 阅读:(61) ⋅ 点赞:(0)

1.十进制转二进制(善于使用__int128)

3373. 进制转换 - AcWing题库

#include<bits/stdc++.h>
using namespace std;
__int128 x;
int x_;
string s1;
int main(){
    stack<int> s;
    while(cin>>s1){
        int len=s1.size();
        for(int i=0;i<len;i++){
            x=x*10+(s1[i]-'0');
        }
        while(x){
            s.push(x%2);
            x=x/2;
        }
        if(s.empty()){
            cout<<0<<endl;
            continue;
        }
        while(!s.empty()){
            cout<<s.top();
            s.pop();
        }
        cout<<endl;
    }
    return 0;
}

 2.十六进制转十进制(考虑负数)

3452. 进制转换 - AcWing题库

#include<bits/stdc++.h>
using namespace std;
int x;
string s;
unordered_map<char,int> hmap;
int main(){
    hmap['A']=10,hmap['B']=11,hmap['C']=12,hmap['D']=13,hmap['E']=14,hmap['F']=15;
    hmap['a']=10,hmap['b']=11,hmap['c']=12,hmap['d']=13,hmap['e']=14,hmap['f']=15;
    while(cin>>s){
        x=0;
        int end_=2;
        if(s[0]=='-'){cout<<'-';end_=3;}
        int len=s.size();
        for(int i=end_;i<len;i++){
            int temp=0;
            if(s[i]>='0'&&s[i]<='9'){
                temp=s[i]-'0';
            }
            else{
                temp=hmap[s[i]];
            }
            x=x*16+temp;
            //cout<<x<<endl;
        }
        cout<<x<<endl;
    }
    return 0;
}

简洁版:(带不带0x都可以转换成功,hex:16,oct:8,dec:10)

#include<bits/stdc++.h>
using namespace std;
int x;
int main(){
    while(cin>>hex>>x){
        cout<<x<<endl;
    }
    return 0;
}
#include<bits/stdc++.h>
using namespace std;
string s;
int x;
int main(){
    while(cin>>s){
        x=stoi(s,nullptr,16);
        cout<<x<<endl;
    }
    return 0;
}