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;
    }
};
相关推荐
学习路上_write几秒前
FREERTOS_互斥量_创建和使用
c语言·开发语言·c++·stm32·单片机·嵌入式硬件
一起养小猫几秒前
《Java数据结构与算法》第三篇(下)队列全解析:从基础概念到高级应用
java·开发语言·数据结构
WolfGang00732118 分钟前
代码随想录算法训练营Day28 | 509.斐波那契数列、70.爬楼梯、746.使用最小花费爬楼梯
算法
Boop_wu21 分钟前
[Java EE] 多线程进阶(JUC)(2)
java·jvm·算法
pale_moonlight22 分钟前
十、 Scala 应用实践 (上)
大数据·开发语言·scala
6***v41739 分钟前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang
1***s63240 分钟前
Rust在WebAssembly中的应用实践
开发语言·rust·wasm
水痕0141 分钟前
go使用cobra来启动项目
开发语言·后端·golang
scixing1 小时前
函数式编程 第八讲 循环者,递归也
开发语言·c#
2501_941879811 小时前
Python在微服务高并发异步API网关请求处理与智能路由架构中的实践
java·开发语言