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;
    }
};
相关推荐
用户9019518242411 小时前
【征文计划】基于 CXR-M SDK 打造 “AR 眼镜 + 手机” 户外步徒协同导航系统
算法
rengang6611 小时前
08-决策树:探讨基于树结构的分类和回归方法及其优缺点
人工智能·算法·决策树·机器学习·分类·回归
闻缺陷则喜何志丹11 小时前
【剪枝 贪心 回溯】B4093 [CSP-X2021 山东] 发送快递|普及+
c++·算法·剪枝·贪心·洛谷
猫头虎11 小时前
HAMi 2.7.0 发布:全面拓展异构芯片支持,优化GPU资源调度与智能管理
嵌入式硬件·算法·prompt·aigc·embedding·gpu算力·ai-native
.ZGR.11 小时前
C语言:数组的增删查改2.0
c语言·开发语言
漫漫不慢.11 小时前
算法练习-二分查找
java·开发语言·算法
如竟没有火炬12 小时前
LRU缓存——双向链表+哈希表
数据结构·python·算法·leetcode·链表·缓存
Greedy Alg12 小时前
LeetCode 236. 二叉树的最近公共祖先
算法
掘根12 小时前
【Qt】绘图
开发语言·qt
Maple_land12 小时前
Linux进程第八讲——进程状态全景解析(二):从阻塞到消亡的完整生命周期
linux·运维·服务器·c++·centos