预先写好要编码的字符串HEX,通过下标索引。

#include <iostream>
#include <string>
using namespace std;

string toHexString(int n);

int main() {

    int n;
    cin >> n;

    string hexStr = toHexString(n);
    cout << hexStr << endl;

    return 0;
}

string toHexString(int n) {
    // write your code here......
    string out = "";
    string HEX = "0123456789ABCDEF";
    while (n != 0) {
        int k = n % 16;
        out = HEX[k] + out;
        n = n / 16;
    }
    return out;
}