题解 | #十进制整数转十六进制字符串#

十进制整数转十六进制字符串

https://www.nowcoder.com/practice/80eca5f47e6f473893151b863b25aba1

#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......
    if (n == 0) {
        return "0";
    }

    const string HEX = "0123456789ABCDEF";
    string str = "";
    bool isNegative = n < 0;

    if (isNegative) {
        n = -n;
    }

    while (n != 0) {
        int index = n % 16;
        str += HEX[index];
        n /= 16;
    }

    int len = str.length();
    for (int i = 0; i < len / 2; i++) {
        char t = str[i];
        str[i] = str[len - i - 1];
        str[len - i - 1] = t;
    }

    if (isNegative) {
        str = "-" + str;
    }

    return str;
}

全部评论

相关推荐

有趣的牛油果开挂了:最近这个阶段收到些杂七杂八的短信是真的烦
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务