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

二、题解

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;
    }
};

相关推荐

  1. LeetCode 45

    2024-02-18 23:14:01       69 阅读
  2. leetcode40

    2024-02-18 23:14:01       36 阅读
  3. leetcode(402,44 53)

    2024-02-18 23:14:01       60 阅读
  4. LeetCode--455.分发饼干

    2024-02-18 23:14:01       56 阅读
  5. leetcode 455.分发饼干

    2024-02-18 23:14:01       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-18 23:14:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-18 23:14:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-18 23:14:01       82 阅读
  4. Python语言-面向对象

    2024-02-18 23:14:01       91 阅读

热门阅读

  1. 使用Typescript对Axios进行二次封装

    2024-02-18 23:14:01       48 阅读
  2. 【矩阵】托普利茨矩阵

    2024-02-18 23:14:01       55 阅读
  3. 第三届全国电子取证比武复盘wp(案例一)

    2024-02-18 23:14:01       47 阅读
  4. pytorch: ground truth similarity matrix

    2024-02-18 23:14:01       58 阅读
  5. 学习总结12

    2024-02-18 23:14:01       46 阅读
  6. Sora模型:开启视觉生成新纪元

    2024-02-18 23:14:01       49 阅读
  7. 深入理解C语言函数指针:揭开背后的机制与应用

    2024-02-18 23:14:01       63 阅读
  8. Request 爬虫的 SSL 连接问题深度解析

    2024-02-18 23:14:01       51 阅读
  9. 「优选算法刷题」:判定字符是否唯一

    2024-02-18 23:14:01       50 阅读
  10. 动态规划-树形DP入门-自上而下树形DP

    2024-02-18 23:14:01       60 阅读
  11. Python入门:常用模块—xml模块

    2024-02-18 23:14:01       45 阅读
  12. 图神经网络中的边的预测问题

    2024-02-18 23:14:01       53 阅读
  13. 编译相关内容(自用)

    2024-02-18 23:14:01       40 阅读
  14. 前端的开发规范

    2024-02-18 23:14:01       53 阅读