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;
    }
};
相关推荐
独自破碎E1 天前
【归并】单链表的排序
数据结构·链表
汤姆yu1 天前
基于python大数据的协同过滤音乐推荐系统
大数据·开发语言·python
爱学习的小道长1 天前
Python Emoji库的使用教程
开发语言·python
汽车仪器仪表相关领域1 天前
工况模拟精准检测,合规减排赋能行业 ——NHASM-1 型稳态工况法汽车排气检测系统项目实战经验分享
数据库·算法·单元测试·汽车·压力测试·可用性测试
L_09071 天前
【C++】高阶数据结构 -- 平衡二叉树(AVLTree)
数据结构·c++
今儿敲了吗1 天前
C++概述
c++·笔记
冰冰菜的扣jio1 天前
Redis基础数据结构
数据结构·数据库·redis
chilavert3181 天前
技术演进中的开发沉思-299 计算机原理:数据结构
算法·计算机原理
Sammyyyyy1 天前
Symfony AI 正式发布,PHP 原生 AI 时代开启
开发语言·人工智能·后端·php·symfony·servbay
C+-C资深大佬1 天前
C++逻辑运算
开发语言·c++·算法