进制转换问题

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;
}

相关推荐

  1. (二).数值&转换

    2024-04-26 10:04:03       38 阅读
  2. Python的转换

    2024-04-26 10:04:03       56 阅读
  3. C/C++转换

    2024-04-26 10:04:03       53 阅读
  4. C++:万能转换

    2024-04-26 10:04:03       39 阅读
  5. go语言10与16转换

    2024-04-26 10:04:03       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-26 10:04:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-26 10:04:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-26 10:04:03       82 阅读
  4. Python语言-面向对象

    2024-04-26 10:04:03       91 阅读

热门阅读

  1. Android TV 桌面图标闪

    2024-04-26 10:04:03       35 阅读
  2. docker 部署 kafka-ui

    2024-04-26 10:04:03       28 阅读
  3. React 语法

    2024-04-26 10:04:03       33 阅读
  4. Elasticsearch

    2024-04-26 10:04:03       33 阅读
  5. 【算法模版】基础算法

    2024-04-26 10:04:03       23 阅读
  6. Visual Studio Code 快捷键大全

    2024-04-26 10:04:03       29 阅读
  7. Ubuntu 系统使用 root 用户登录

    2024-04-26 10:04:03       28 阅读
  8. 【测试杂谈】论敏捷测试的技巧

    2024-04-26 10:04:03       35 阅读
  9. React 之 函数式组件(二)

    2024-04-26 10:04:03       26 阅读
  10. 验证服务器网络端口是否可访问

    2024-04-26 10:04:03       33 阅读
  11. 机器学习之增强学习DQN(Deep Q Network)

    2024-04-26 10:04:03       31 阅读
  12. cos + vue + Element UI 上传文件的实现

    2024-04-26 10:04:03       38 阅读