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;
    }
};
相关推荐
利威尔xu2 小时前
Go channel 关闭 3 个 panic:向已关闭 channel 发送,服务当场崩溃
开发语言·后端·golang·并发编程·channel
xys_6782 小时前
JavaSE通关手册:数组
数据结构
电科_银尘2 小时前
【大模型算法与工程 09】SGD、Momentum与AdamW:优化器如何选择
人工智能·算法
山楂树の2 小时前
Java BigDecimal笔记
java·开发语言
货拉拉技术3 小时前
视觉底座:货拉拉OCR的进阶之路
算法
__underline__4 小时前
冷门Python知识点005篇:list.sort( )的排序稳定性,是用0字节额外内存实现的
python·算法
Java展博5 小时前
[Go 后端转场] 从 try-catch 到 if err != nil:写惯 Java 的人第一次上手最别扭的 4 件事
java·开发语言·golang
SEO_juper5 小时前
Node.js 全站 SEO 体检报告生成器:一次查完标题、描述、canonical、H1、图片
开发语言·前端·node.js·html·bash
风落青芜6 小时前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
H H.9 小时前
Java企业级开发:从框架到工程化实战
java·开发语言·经验分享·其他·课程设计