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 分钟前
Visual Studio中的常用调试功能(下)
c++·ide·visual studio·调试
武当豆豆19 分钟前
C++编程学习(第25天)
开发语言·c++·学习
地平线开发者1 小时前
征程 6 | PTQ 精度调优辅助代码,总有你用得上的
算法·自动驾驶
Tisfy2 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率
-Xie-2 小时前
Maven(二)
java·开发语言·maven
mftang2 小时前
Python可视化工具-Bokeh:动态显示数据
开发语言·python
m0_480502642 小时前
Rust 入门 生命周期-next2 (十九)
开发语言·后端·rust
IT利刃出鞘2 小时前
Java线程的6种状态和JVM状态打印
java·开发语言·jvm
CoovallyAIHub2 小时前
为高空安全上双保险!无人机AI护航,YOLOv5秒判安全带,守护施工生命线
深度学习·算法·计算机视觉
huangzixuan10072 小时前
08.18总结
算法·深度优先·图论