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 分钟前
用for循环语句求和
开发语言·人工智能·学习·matlab·学习方法
萌新小码农‍5 分钟前
人工智能数学基础+python实例(人工智能学习day3)
开发语言·人工智能·python
Lumbrologist8 分钟前
【C++】零基础入门 · 第 1 节:第一个程序 Hello World 与编译运行
开发语言·c++
超梦dasgg25 分钟前
Java 生产环境 MQ 技术选型全解析
java·开发语言·java-rocketmq·java-rabbitmq
_李小白41 分钟前
【C++学习笔记】新特性之inline变量
c++·笔记·学习
心中有国也有家44 分钟前
hccl 架构拆解:昇腾集合通信库到底在做什么?
人工智能·经验分享·笔记·分布式·算法·架构
桀人1 小时前
C++——模板初阶(收录在专栏C++入门到精通)
开发语言·c++
一直有一个ac的梦想1 小时前
cmu15445 2025fall lec 18 transactions with two-phase lock
java·开发语言·数据库
小O的算法实验室1 小时前
2026年MCS,Q-learning增强MOPSO与改进DWA融合算法+复杂三维地形下特定移动机器人动态路径规划
算法