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;
    }
};
相关推荐
星栈独行11 小时前
翻完 Pi 源码:它和 Codex、Claude Code 有何不同
开发语言·javascript·人工智能·程序人生
2601_9545267511 小时前
【工业传感与算法实战】温漂补偿与零点抗漂破局:基于二阶多项式拟合的 C/C++ 边缘校准算法,深度拆解“压力变送器什么牌子好”的技术硬指标
c语言·c++·算法
qq_4480111611 小时前
C语言中的变量和函数的定义与声明
android·c语言·开发语言
code_pgf11 小时前
`unordered_map` 详解
c++
叩码以求索12 小时前
浅谈:算法萌新如何高效刷题应对面试(一)
算法·面试·职场和发展
孫治AllenSun12 小时前
【DataX】生产环境搭建DataX集群案例
java·开发语言·jvm
一拳一个呆瓜13 小时前
【STL】iostream 编程:检测提取操作产生的错误
c++·stl
稚南城才子,乌衣巷风流13 小时前
判断素数与拓展应用
c++
众少成多积小致巨13 小时前
C++ 规范参考(下)
c++
c2385613 小时前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法