东华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;
}
相关推荐
前端摸鱼匠3 小时前
【AI大模型春招面试题11】什么是模型的“涌现能力”(Emergent Ability)?出现条件是什么?
人工智能·算法·ai·自然语言处理·面试·职场和发展
sqmw3 小时前
MFCMouseEffect:把桌面输入反馈这件事,做成一个真正可扩展的引擎
c++·插件·引擎·鼠标特效·键鼠指示·鼠标伴宠
globaldomain3 小时前
什么是用于长距离高速传输的TCP窗口扩展?
开发语言·网络·php
MORE_773 小时前
leecode-合并区间-贪心算法
算法·贪心算法
沈阳信息学奥赛培训3 小时前
#undef 指令 (C/C++)
c语言·开发语言·c++
2401_873204653 小时前
分布式系统安全通信
开发语言·c++·算法
Dxy12393102164 小时前
JS发送请求的方法详解
开发语言·javascript·ecmascript
sw1213894 小时前
C++中的代理模式实战
开发语言·c++·算法
難釋懷4 小时前
Lua语法入门-条件控制、函数
开发语言·junit·lua
桌面运维家5 小时前
Win10打印机共享故障排查:权限与网络配置详解
开发语言·网络·php