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;
    }
};
相关推荐
我是唐青枫几秒前
C#.NET Monitor 与 Mutex 深入解析:进程内同步、跨进程互斥与使用边界
开发语言·c#·.net
bbq粉刷匠1 分钟前
Java--剖析synchronized
java·开发语言
ou.cs4 分钟前
c# 信号量和锁的区别
开发语言·c#
Gofarlic_OMS5 分钟前
装备制造企业Fluent许可证成本分点典型案例
java·大数据·开发语言·人工智能·自动化·制造
汀、人工智能6 分钟前
[特殊字符] 第57课:搜索旋转排序数组
数据结构·算法·数据库架构·图论·bfs·搜索旋转排序数组
倦王10 分钟前
力扣日刷47
算法·leetcode·职场和发展
MicroTech202513 分钟前
突破量子数据加载瓶颈,MLGO微算法科技推出面向大规模量子计算的分治态制备技术
科技·算法·量子计算
码王吴彦祖14 分钟前
顶象 AC 纯算法迁移实战:从补环境到纯算的完整拆解
java·前端·算法
Freak嵌入式15 分钟前
MicroPython LVGL基础知识和概念:显示与多屏管理
开发语言·python·github·php·gui·lvgl·micropython
SccTsAxR19 分钟前
算法基石:手撕离散化、递归与分治
c++·经验分享·笔记·算法