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;
    }
};
相关推荐
软件黑马王子3 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
闲猫3 小时前
go orm GORM
开发语言·后端·golang
计算机小白一个3 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
万事可爱^4 小时前
HDBSCAN:密度自适应的层次聚类算法解析与实践
算法·机器学习·数据挖掘·聚类·hdbscan
黑不溜秋的4 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
李白同学4 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
黑子哥呢?6 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash
青龙小码农6 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿6 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!6 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode