LeetCode 题解工作台
七进制数
给定一个整数 num ,将其转化为 7 进制 ,并以字符串形式输出。 示例 1: 输入: num = 100 输出: "202" 示例 2: 输入: num = -7 输出: "-10" 提示: -10 7 7
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数学·string
答案摘要
我们不妨假设 `num` 大于等于 ,那么,如果 `num` 等于 ,只需要返回 即可。否则,我们将 模 的结果保存起来,最后逆序拼接成字符串即可。 时间复杂度 $O(\log n)$,忽略答案的空间消耗,空间复杂度 。其中 是 `num` 的绝对值大小。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
给定一个整数 num,将其转化为 7 进制,并以字符串形式输出。
示例 1:
输入: num = 100 输出: "202"
示例 2:
输入: num = -7 输出: "-10"
提示:
-107 <= num <= 107
解题思路
方法一:模拟
我们不妨假设 num 大于等于 ,那么,如果 num 等于 ,只需要返回 即可。否则,我们将 模 的结果保存起来,最后逆序拼接成字符串即可。
时间复杂度 ,忽略答案的空间消耗,空间复杂度 。其中 是 num 的绝对值大小。
class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return '0'
if num < 0:
return '-' + self.convertToBase7(-num)
ans = []
while num:
ans.append(str(num % 7))
num //= 7
return ''.join(ans[::-1])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log7|num|) because each division reduces the number by a factor of 7. Space complexity is also O(log7|num|) to store the resulting digits in a string. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Are you handling negative numbers correctly with a leading '-' sign?
- question_mark
Can you perform the conversion without using built-in base functions?
- question_mark
Are you efficiently building the string from the remainders to avoid order issues?
常见陷阱
外企场景- error
Forgetting to prepend '-' for negative numbers can cause incorrect output.
- error
Reversing the digits incorrectly when joining remainders results in wrong base 7 string.
- error
Using float division instead of integer division may produce unexpected results.
进阶变体
外企场景- arrow_right_alt
Convert an integer to any arbitrary base k as a string.
- arrow_right_alt
Handle very large integers efficiently using string concatenation only.
- arrow_right_alt
Convert a list of integers to their base 7 strings in batch processing.