LeetCode 题解工作台

七进制数

给定一个整数 num ,将其转化为 7 进制 ,并以字符串形式输出。 示例 1: 输入: num = 100 输出: "202" 示例 2: 输入: num = -7 输出: "-10" 提示: -10 7 7

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·string

bolt

答案摘要

我们不妨假设 `num` 大于等于 ,那么,如果 `num` 等于 ,只需要返回 即可。否则,我们将 模 的结果保存起来,最后逆序拼接成字符串即可。 时间复杂度 $O(\log n)$,忽略答案的空间消耗,空间复杂度 。其中 是 `num` 的绝对值大小。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个整数 num,将其转化为 7 进制,并以字符串形式输出。

 

示例 1:

输入: num = 100
输出: "202"

示例 2:

输入: num = -7
输出: "-10"

 

提示:

  • -107 <= num <= 107
lightbulb

解题思路

方法一:模拟

我们不妨假设 num 大于等于 00,那么,如果 num 等于 00,只需要返回 00 即可。否则,我们将 numnum77 的结果保存起来,最后逆序拼接成字符串即可。

时间复杂度 O(logn)O(\log n),忽略答案的空间消耗,空间复杂度 O(1)O(1)。其中 nnnum 的绝对值大小。

1
2
3
4
5
6
7
8
9
10
11
12
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])
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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?

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

七进制数题解:数学·string | LeetCode #504 简单