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;
    }
};
相关推荐
Wadli1 分钟前
26.单调栈
算法
晨曦夜月3 分钟前
进程的五大状态及特殊进程解析
linux·服务器·算法
24白菜头7 分钟前
【无标题】
c++·笔记·学习·harmonyos
qq_589568107 分钟前
java基础学习,案例练习,即时通讯
java·开发语言·学习
吟安安安安7 分钟前
适合短期冲刺的学习工作流(针对算法)
学习·算法
科研前沿12 分钟前
什么是时空融合技术?
大数据·人工智能·数码相机·算法·重构·空间计算
DevilSeagull16 分钟前
Windows 批处理 (Batch) 编程: 从入门到入土. (一) 基础概念与环境配置
开发语言·windows·后端·batch·语言
AI科技星17 分钟前
全域数学本源公理:0、1、∞ 三者核心关系 (典籍定稿版)
人工智能·算法·数学建模·数据挖掘·量子计算
AI科技星22 分钟前
全域数学·第卷:场计算机卷(场空间计算机)【乖乖数学】
java·开发语言·人工智能·算法·机器学习·数学建模·数据挖掘
Deepoch24 分钟前
数学模型驱动:Deepoc 低幻觉数学大模型助力发动机全周期智能优化
人工智能·算法·机器学习·deepoc·数学大模型·低幻觉