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;
    }
};
相关推荐
Jackson@ML1 小时前
如何快速高效学习Python?
开发语言·python
飞桨PaddlePaddle2 小时前
Wan2.1和HunyuanVideo文生视频模型算法解析与功能体验丨前沿多模态模型开发与应用实战第六期
人工智能·算法·百度·音视频·paddlepaddle·飞桨·deepseek
西瓜本瓜@2 小时前
在Android中如何使用Protobuf上传协议
android·java·开发语言·git·学习·android-studio
UFIT2 小时前
Python函数与模块笔记
开发语言·python
机智的人猿泰山2 小时前
java kafka
java·开发语言·kafka
Y1nhl3 小时前
搜广推校招面经八十一
开发语言·人工智能·pytorch·深度学习·机器学习·推荐算法·搜索算法
Algorithm15763 小时前
谈谈接口和抽象类有什么区别?
java·开发语言
Starry_hello world3 小时前
C++ 快速幂算法
c++·算法·有问必答
yu4106213 小时前
Rust 语言使用场景分析
开发语言·后端·rust
良艺呐^O^3 小时前
uniapp实现app自动更新
开发语言·javascript·uni-app