LeetCode 题解工作台
数字转换为十六进制数
给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。 答案字符串中的所有字母都应该是小写字符,并且除了 0 本身之外,答案中不应该有任何前置零。 注意: 不允许使用任何由库提供的将数字直接转换或格式化为十六进制的方法来解决这个问题。 示例 1: 输入: nu…
3
题型
4
代码语言
3
相关题
当前训练重点
简单 · 数学·string
答案摘要
class Solution: def toHex(self, num: int) -> str:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。
答案字符串中的所有字母都应该是小写字符,并且除了 0 本身之外,答案中不应该有任何前置零。
注意: 不允许使用任何由库提供的将数字直接转换或格式化为十六进制的方法来解决这个问题。
示例 1:
输入:num = 26 输出:"1a"
示例 2:
输入:num = -1 输出:"ffffffff"
提示:
-231 <= num <= 231 - 1
解题思路
方法一
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return '0'
chars = '0123456789abcdef'
s = []
for i in range(7, -1, -1):
x = (num >> (4 * i)) & 0xF
if s or x != 0:
s.append(chars[x])
return ''.join(s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log16 N) because each division reduces the number by a factor of 16. Space complexity is O(1) for calculation plus O(log16 N) for the string result. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate correctly handles negative integers with two's complement conversion.
- question_mark
Listen for explicit use of modulus and division or bit manipulation rather than built-in conversion functions.
- question_mark
Verify that the string is built in the correct order and uses lowercase characters without extra leading zeros.
常见陷阱
外企场景- error
Forgetting to handle negative numbers using two's complement, leading to incorrect outputs.
- error
Appending digits instead of prepending, which reverses the hexadecimal string.
- error
Using uppercase letters or including leading zeros incorrectly.
进阶变体
外企场景- arrow_right_alt
Convert a number to octal representation using similar math and string techniques.
- arrow_right_alt
Support 64-bit integers while preserving two's complement handling and correct string formatting.
- arrow_right_alt
Return the hexadecimal representation with a fixed width of 8 characters, padding with zeros as needed.