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;
    }
};
相关推荐
YaoYuan93232 小时前
C++ 类型推导(第一部分)
c++
HAH-HAH2 小时前
【Python 入门】(2)Python 语言基础(变量)
开发语言·python·学习·青少年编程·个人开发·变量·python 语法
递归不收敛2 小时前
一、Java 基础入门:从 0 到 1 认识 Java(详细笔记)
java·开发语言·笔记
夜猫逐梦3 小时前
【VC】 error MSB8041: 此项目需要 MFC 库
c++·mfc
纪元A梦3 小时前
贪心算法应用:配送路径优化问题详解
算法·贪心算法
zhangfeng11333 小时前
win7 R 4.4.0和RStudio1.25的版本兼容性以及系统区域设置有关 导致Plots绘图面板被禁用,但是单独页面显示
开发语言·人工智能·r语言·生物信息
姓刘的哦4 小时前
Qt中的QWebEngineView
数据库·c++·qt
C_player_0014 小时前
——贪心算法——
c++·算法·贪心算法
SundayBear4 小时前
QT零基础入门教程
c++·qt
子午5 小时前
Python的uv包管理工具使用
开发语言·python·uv