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 分钟前
ArrayList和LinkedList
java·开发语言
孚亭18 分钟前
Swift添加字体到项目中
开发语言·ios·swift
hweiyu0022 分钟前
Go、DevOps运维开发实战(视频教程)
开发语言·golang·运维开发
William_wL_31 分钟前
【C++】内存管理
c++
mm-q291522272933 分钟前
Python+Requests零基础系统掌握接口自动化测试
开发语言·python
星星火柴9361 小时前
笔记 | C++面向对象高级开发
开发语言·c++·笔记·学习
Coovally AI模型快速验证1 小时前
当视觉语言模型接收到相互矛盾的信息时,它会相信哪个信号?
人工智能·深度学习·算法·机器学习·目标跟踪·语言模型
码界奇点1 小时前
Rust 性能优化全流程从 flamegraph 定位瓶颈到 unsafe 与 SIMD 加速响应快
开发语言·性能优化·rust·simulated annealing
悲伤小伞2 小时前
Linux_Socket_UDP
linux·服务器·网络·c++·网络协议·udp
电院工程师2 小时前
SIMON64/128算法Verilog流水线实现(附Python实现)
python·嵌入式硬件·算法·密码学