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;
    }
};
相关推荐
CoderCodingNo2 分钟前
【GESP】C++四级真题 luogu-B4416 [GESP202509 四级] 最长连续段
开发语言·c++·算法
xjxijd3 分钟前
工业元宇宙 IDC 支撑:数字孪生算法 + 边缘服务器,生产调度响应速度提 3 倍
运维·服务器·算法
a程序小傲5 分钟前
京东Java面试被问:Fork/Join框架的使用场景
java·开发语言·后端·postgresql·面试·职场和发展
⑩-9 分钟前
Java四种线程创建方式
java·开发语言
月光在发光10 分钟前
22_GDB调试记录(未完成)
java·开发语言
222you12 分钟前
SpringAOP的介绍和入门
java·开发语言·spring
程序员zgh13 分钟前
代码重构 —— 读后感
运维·c语言·开发语言·c++·重构
蒙奇D索大18 分钟前
【数据结构】考研408 | 平方探测法精讲:跳跃探查的艺术与聚集迷思
数据结构·笔记·考研·改行学it
xwz小王子19 分钟前
UniBYD:超越人类示教模仿的跨实体机器人操作学习统一框架
学习·算法·机器人·跨实体
liulilittle21 分钟前
moodycamel::ConcurrentQueue 清空队列的方法论
开发语言·c++