东华OJ-基础题-107-16进制加法(C++)

  • 问题描述
    某天、小晨在路上背着单词,突遇一外星人,外星人对小晨很感兴趣,为了考验小晨的智商,就向小晨提问简单加法,由于外星人使用16进制,所以,小晨必须用16进制回答。
  • 输入说明
    首先输入一个整数T,

以下T行,每行两个16进制数字

  • 输出说明
    T行,每行一个16进制数,为求出的两数之和。

其中的英文字母a到f为小写。

  • 输入范例
cpp 复制代码
2
4b0d 4887
2745 7438
  • 输出范例
cpp 复制代码
9394
9b7d

感想:使用了unordered_map<char,int> 将十六进制转为纯数字。
代码如下:

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

struct add {
    string a;
    string b;
};

int main() {
    int n;
    cin>>n;
    vector<add> arr(n);
    for(int i = 0; i<n; ++i) {
        cin>>arr[i].a>>arr[i].b;
    }
    unordered_map<char,int> map = {{'1',1},{'2',2},{'3',3},{'4',4},{'5',5},{'6',6},{'7',7},
        {'8',8},{'9',9},{'a',10},{'b',11},{'c',12},{'d',13},{'e',14},{'f',15}
    };
    for(int i =0; i<n; ++i) {
        string temp_a = arr[i].a,temp_b = arr[i].b;
        string ans;
        int j = temp_a.size();
        int k = temp_b.size();
        int carry = 0,add;
        while(j&&k) {
            add = map[temp_a[--j]]+map[temp_b[--k]]+carry;
            carry = add/16;
            if(add%16>=10) {
                char target = add%16-10 +'a';
                ans = target+ans;
            } else
                ans = to_string(add%16)+ans;
        }
        while(j) {
            add = map[temp_a[--j]]+ carry;
            carry = add/16;
            if(add%16>=10) {
                char target = 'a'+ add%16-10;
                ans = target+ans;
            } else
                ans = to_string(add%16)+ans;
        }

        while(k) {
            add = map[temp_b[--k]]+ carry;
            carry = add/16;
            if(add%16>=10) {
                char target = 'a'+ add%16-10;
                ans = target+ans;
            } else
                ans = to_string(add%16)+ans;
        }

        if(carry) ans = to_string(carry) + ans;
        cout<<ans<<endl;
    }

    return 0;
}
相关推荐
机器学习之心12 小时前
集成BWM法、熵权法、改进博弈论组合赋权与三角直觉模糊云模型的多属性评价模型,MATLAB代码
开发语言·matlab·熵权法·三角直觉模糊云模型·bwm法·改进博弈论组合赋权·多属性评价模型
子兮曰13 小时前
whisper.cpp 深度解析:从边缘设备到实时语音识别
前端·c++·后端
雪碧聊技术13 小时前
上午题_算法
算法·软考·软件设计师
特种加菲猫13 小时前
二叉搜索树:数据世界的“快速寻路指南”
开发语言·c++
naturerun13 小时前
从数组中删除元素的算法
数据结构·c++·算法
特种加菲猫13 小时前
STL关联容器:Set/Multiset与Map/Multimap详解
开发语言·c++
我滴老baby13 小时前
0基础速通Python+AI|2026热门轻量化玩法全攻略:从入门到实战,3天搞定AI应用开发
开发语言·人工智能·python
一个天蝎座 白勺 程序猿13 小时前
Python(29)Python生成器函数深度解析:asyncio事件循环的底层实现与异步编程实战
开发语言·python
2zcode13 小时前
原创文档:基于MATLAB的线性预测编码变声器系统
开发语言·matlab·语音识别
七夜zippoe13 小时前
Python RESTful API设计终极指南:从理论到企业级实战
开发语言·python·http·pandas·restful api