405. Convert a Number to Hexadecimal【E】【leetcode】

本文介绍了一种将整数转换为十六进制字符串的算法,并提供了详细的Python实现示例。该算法适用于正数、负数(使用二进制补码)及零的情况,并确保输出格式符合规范。

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:

Input:
26

Output:
"1a"

Example 2:

Input:
-1

Output:
"ffffffff"

Subscribe to see which companies asked this question


最下面的是不要脸版本,当然了,太不要脸了,所以呢,只需要自己实现一下hex这个函数就行

怎么实现呢,那就是一个循环,不断地除以16,然后转化成十六进制就行了


class Solution(object):
    def toHex(self, num):
        def change(num):
            res = ''
            hex = ['a','b','c','d','e','f']
            for i in num[::-1]:
                #print i
                if i > 9:
                    res += hex[i%10]
                else:
                    res += str(i)
            return res


        def f(num):
            #print '```'
            res = []
            while num > 0:
                #print num
                res += num % 16,
                num /= 16
                #print num
            return  res

        if num == 0:
            return '0'
        if num < 0:
            num += (1 << 32)
        res = f(num)
        #print res
        return change(res)


### ✅ 题目:T0119 将十六进制整数转换为十进制数 **Write a C/C++ program to convert hexadecimal integer to decimal number.** --- ### 📥 输入格式: - 一个十六进制整数(如 `0x1A`、`1B`、`FF`、`-0x20` 等) ### 📤 输出格式: - 对应的十进制整数 --- ### ✅ 样例输入 #1: ``` 1A ``` ### ✅ 样例输出 #1: ``` 26 ``` ### ✅ 样例输入 #2: ``` FF ``` ### ✅ 样例输出 #2: ``` 255 ``` ### ✅ 样例输入 #3: ``` -0x20 ``` ### ✅ 样例输出 #3: ``` -32 ``` --- ## ✅ 解题思路: 在 C/C++ 中,可以使用标准输入函数自动识别十六进制数: - `std::cin` 和 `scanf` 支持读取十六进制整数 - 只要输入以 `0x` 或 `0X` 开头,或只是纯十六进制数字(如 `A1`),我们可以用合适的方式解析 但注意:C++ 默认能自动识别带 `0x` 的十六进制字符串为整数。 --- ## ✅ 方法一:使用 `cin` + `hex` 流控制符(推荐) ```cpp #include <iostream> using namespace std; int main() { int n; cin >> hex >> n; // 告诉 cin 当前输入是十六进制 cout << n << endl; // 自动输出为十进制 return 0; } ``` > 💡 `hex` 是输入流的操纵符,表示接下来从输入读取的整数按十六进制解析。 --- ### ✅ 示例运行: | 输入 | 输出 | |----------|------| | `1A` | `26` | | `FF` | `255`| | `-0x20` | `-32`| ✅ 完全支持正负数和 `0x` 前缀! --- ## ✅ 方法二:使用 `scanf` 解析十六进制 ```cpp #include <cstdio> using namespace std; int main() { int n; scanf("%x", &n); // %x 表示读取十六进制无符号整数(但可处理负号) printf("%d\n", n); return 0; } ``` > ⚠️ 注意:`%x` 不直接支持负号 `-`。如果输入 `-1A`,会出错。 ### ✅ 改进版:支持负号的手动判断 ```cpp #include <cstdio> #include <cctype> #include <iostream> using namespace std; int main() { string hexStr; cin >> hexStr; int result = 0; int sign = 1; size_t i = 0; // 处理负号 if (hexStr[0] == '-') { sign = -1; i = 1; } // 跳过 "0x" 或 "0X" if (hexStr[i] == '0' && (hexStr[i+1] == 'x' || hexStr[i+1] == 'X')) { i += 2; } // 手动转换十六进制字符到十进制 for (; i < hexStr.size(); ++i) { char c = toupper(hexStr[i]); result = result * 16 + (c >= 'A' ? c - 'A' + 10 : c - '0'); } cout << sign * result << endl; return 0; } ``` --- ### 🔍 方法对比: | 方法 | 优点 | 缺点 | |------|------|------| | `cin >> hex >> n` | 简洁、安全、标准 | 需要知道输入一定是 hex | | `scanf("%x")` | 快速 | 不支持负号 | | 手动解析字符串 | 完全可控,支持各种格式 | 代码较长 | --- ## ✅ 推荐最终简洁写法(竞赛/练习常用): ```cpp #include <iostream> using namespace std; int main() { int n; cin >> hex >> n; cout << n << endl; return 0; } ``` 这行 `cin >> hex >> n;` 能正确识别: - `1A` - `0xFF` - `-1A` - `-0x20` 全部都能转成对应的十进制! ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值