LeetCode405. Convert a Number to Hexadecimal

文章目录

一、题目

Given an integer num, return a string representing its hexadecimal representation. For negative integers, two's complement method is used.

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

Note: You are not allowed to use any built-in library method to directly solve this problem.

Example 1:

Input: num = 26

Output: "1a"

Example 2:

Input: num = -1

Output: "ffffffff"

Constraints:

-231 <= num <= 231 - 1

二、题解

cpp 复制代码
class Solution {
public:
    string toHex(int num) {
        if(num == 0) return "0";
        string res = "";
        while(num != 0){
            int u = num & 15;
            char c = u + '0';
            if(u >= 10) c = (u - 10 + 'a');
            res += c;
            //逻辑右移
            num = (unsigned int)num >> 4;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};
相关推荐
地平线开发者5 分钟前
征程 6 | 工具链 QAT ObserverBase 源码解析
算法
卷无止境12 分钟前
C++ 存储类说明符(Storage Class Specifier)大横评
c++·后端
卷无止境22 分钟前
C++ 编程的一大坑:非常量全局变量是"万恶之源"
c++·后端
C语言小火车23 分钟前
C++ 快速排序(Quick Sort)深度精讲:分治思想、Lomuto 分区法及三数取中优化,面试手撕必会
c语言·开发语言·c++·面试·排序算法·快速排序
sycmancia23 分钟前
Qt——多线程间的互斥
开发语言·qt
地平线开发者27 分钟前
【地平线 征程 6 工具链进阶教程】QAT 训练常见问题和排查
算法
地平线开发者29 分钟前
征程 6 | 直方图量化配置与校准实例
算法
一知半解仙35 分钟前
2026年彻底免费的辅助编程Agent大模型汇总
开发语言·人工智能·开源
Mr-Wanter1 小时前
wsl2 jdk管理工具之sdkman
java·开发语言·sdkman